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

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


I know this is an old thread and that Samuel probably fixed his issue a long time ago. However, I had the same problem and came across this post while google'ing. Found a solution and think it is worthwhile to add.

You can use the shutdown method on the socket class. It can prevent further sends, receives or both.

socket.shutdown(socket.SHUT_WR)

The above prevents future sends, as an example.

See Python docs for more info.


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: ", dataself.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 = Falsetry:    r, _, _ = select.select([self.clientSocket], [], [])    do_read = bool(r)except socket.error:    passif do_read:    data = self.clientSocket.recv(1024)    print "Got data: ", data    self.clientSocket.send(data)


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

# Echo server programimport socketfrom threading import Threadimport timeclass 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 = 6000serverSocket = 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: ', addrclientThread = ClientThread(clientSocket)clientThread.start()# Close it down immediatly clientSocket.close()