Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am programming a simple server-based chat program. I am using threads. Everything works fine, but to stop the program, I have to terminate it manually, because the thread, that is searching for new users, won't terminate, because of the socket.accep() function, which is still running. I was trying to fix that, by closing the socket, but somehow, that didn't work out. This is my code for the user search thread:

import socket, time
from threading import Thread
from userHandling import UserHandler

class UserSearcher(Thread):

    def __init__(self):
        print("Thread: User searching is will start now!")
        Thread.__init__(self)

    def run(self):
        self.__uH = UserHandler()
        self.__tcpListener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.__tcpListener.bind(("", 2030))
        self.__tcpListener.listen(5)
        while True:
            try:
                self.__komm, self.__tcpAddr = self.__tcpListener.accept()
                self.__tcpMsg = self.__komm.recv(1024)
                self.__uH.add(self.__tcpMsg.decode(), self.__tcpAddr[0])
            except:
                print("Searching for chat members failed! Is the system shutting down?")
                break

    def stop(self):
        self.__tcpListener.close()
        time.sleep(1)
        print("Thread: User searching will quit NOW!")
        pass

I don't see the mistake :/ Thanks from a python beginner

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
195 views
Welcome To Ask or Share your Answers For Others

1 Answer

Use socket.shutdown() instead of close():

import socket, time
from threading import Thread

class UserSearcher(Thread):

    def __init__(self):
        print("Thread: User searching is will start now!")
        Thread.__init__(self)

    def run(self):
        self.__tcpListener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.__tcpListener.bind(("", 2030))
        self.__tcpListener.listen(5)
        while True:
            try:
                self.__komm, self.__tcpAddr = self.__tcpListener.accept()
                self.__tcpMsg = self.__komm.recv(1024)
                print(self.__tcpMsg)
            except:
                print("Searching for chat members failed! Is the system shutting down?")
                break

    def stop(self):
        self.__tcpListener.shutdown(socket.SHUT_RDWR)
        time.sleep(1)
        print("Thread: User searching will quit NOW!")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...