本文介绍了Python-带套接字的线程不会停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个基于服务器的简单聊天程序.我正在使用线程.一切正常,但是要停止程序,我必须手动终止它,因为正在运行新的socket.accep()函数,正在寻找新用户的线程不会终止.我试图通过关闭套接字来修复该问题,但是以某种方式,它没有解决问题.这是我的用户搜索线程代码:

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

我没有看到错误:/感谢python初学者

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

推荐答案

使用 socket.shutdown() 而不是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!")

这篇关于Python-带套接字的线程不会停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 18:53