How do I abort a socket.recv() from another thread in Python

后端 未结 4 1942
野性不改
野性不改 2021-02-01 22:22

I have a main thread that waits for connection. It spawns client threads that will echo the response from the client (telnet in this case). But say that I want to close down all

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-01 22:58

    I found a solution using timeouts. That will interrupt the recv (actually before the timeout has expired which is nice):

    # Echo server program
    import socket
    from threading import Thread
    import time
    
    
    class ClientThread(Thread):
        def __init__(self, clientSocke):
            Thread.__init__(self)
            self.clientSocket = clientSocket
    
        def run(self):
            while 1:
                try:
                    data = self.clientSocket.recv(1024)
                    print "Got data: ", data
                    self.clientSocket.send(data)
                except socket.timeout: 
                    # If it was a timeout, we want to continue with recv
                    continue
                except:
                    break
    
            self.clientSocket.close()
    
    HOST = ''
    PORT = 6000
    serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    serverSocket.bind((HOST, PORT))
    serverSocket.listen(1)
    
    clientSocket, addr = serverSocket.accept()
    clientSocket.settimeout(1)
    
    print 'Got a new connection from: ', addr
    clientThread = ClientThread(clientSocket)
    clientThread.start()
    
    # Close it down immediatly 
    clientSocket.close()
    

提交回复
热议问题