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

后端 未结 4 1946
野性不改
野性不改 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 23:16

    I don't know if it's possible to do what you're asking, but it shouldn't be necessary. Just don't read from the socket if there is nothing to read; use select.select to check the socket for data.

    change:

    data = self.clientSocket.recv(1024)
    print "Got data: ", data
    self.clientSocket.send(data)
    

    to something more like this:

    r, _, _ = select.select([self.clientSocket], [], [])
    if r:
        data = self.clientSocket.recv(1024)
        print "Got data: ", data
        self.clientSocket.send(data)
    

    EDIT: If you want to guard against the possibility that the socket has been closed, catch socket.error.

    do_read = False
    try:
        r, _, _ = select.select([self.clientSocket], [], [])
        do_read = bool(r)
    except socket.error:
        pass
    if do_read:
        data = self.clientSocket.recv(1024)
        print "Got data: ", data
        self.clientSocket.send(data)
    

提交回复
热议问题