Getting data back from a socket is problematic, because you do no know when it has finished. You'd either need to specify the number of bytes transferred or have some delimeter logic. The function recvall is useful in the case where you do not have knowledge about either or are too busy or lazy to think about it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
import time,socket def recvall(the_socket,timeout=''): #setup to use non-blocking sockets #if no data arrives it assumes transaction is done #recv() returns a string the_socket.setblocking(0) total_data=;data='' begin=time.time() if not timeout: timeout=1 while 1: #if you got some data, then break after wait sec if total_data and time.time()-begin>timeout: break #if you got no data at all, wait a little longer elif time.time()-begin>timeout*2: break wait=0 try: data=the_socket.recv(4096) if data: total_data.append(data) begin=time.time() data='';wait=0 else: time.sleep(0.1) except: pass #When a recv returns 0 bytes, other side has closed result=''.join(total_data) return result
recvall uses non-blocking sockets and keeps on looking for data until data has not arrived for the timeout amount of time.