Search code examples
pythonsocketsrecv

How to correctly use select.select() with someSocket.recv


This is printing "Received":

connection, clientAddr = mysocket.accept()
data = connection.recv(256)
print("Received")

This is printing "Timed out":

connection, clientAddr = mysocket.accept()
mysocket.setblocking(0)

readable, writeable, exceptional = select.select([mysocket], [], [], 5)
if mysocket in readable:
  data = connection.recv(256)
  print("Received")
else:
  print("Timed out")

The problem isn't that the 5 seconds is too short, the data is being received in the first code block within 5 seconds. I tried removing the line, mysocket.setblocking(0), no change. I tried changing if mysocket in readable: to if readable: and also did print(readable), still timed out and printing outputted, "[]".

Edit: I also tried using mysocket.recv(256) in the else block, it received the data.

I'm running this on a Linux.


Solution

  • readable, writeable, exceptional = select.select([mysocket], [], [], 5)
    if mysocket in readable:
      data = connection.recv(256)
    

    You do a select in mysocket (the listener socket) and if select signals available data you do a read on connection (the connection socket). You should do a select on connection if you want to know if you can read from it instead. The select on mysocket should instead be done if you want to know if you can call accept to get another client connection.