The recv
function is blocking by default. This means that the method will halt the control flow, until something is received on this socket. If you call sock1.recv()
and then sock2.recv()
, the second call will only be reached when socket 1 receives something.
You can use the setblocking
method to make recv
non-blocking, causing it to return at once, even if there is nothing to receive. However, then you would probably have to poll both sockets for new bytes to read:
s1.setblocking(False)
s2.setblocking(False)
while True:
# In non-blocking mode, recv throws a socket.error when
# there is nothing to receive.
try: a = s1.recv()
except socket.error: a = None
try: b = s2.recv()
except socket.error: b = None
handle_data(a,b) # Use received bytes at your discretion
You could parallelize the two recv
calls, using either the multiprocessing
or threading
modules:
class SocketThread(threading.Thread):
def run():
while True:
a = self.sock.recv() # This time, recv in blocking mode
handle_data(a)
t1, t2 = SocketThread(), SocketThread()
t1.sock = sock1
t1.start()
t2.sock = sock2
t2.start()