Recv Over Sockets in Python

by oBelIX

EDIT: I wrote this many years ago. There are much better ways of doing this. Please please please, go lookup them up on the internet. Or ask on stackoverflow. If you do what I’ve done it’s going to bite you in the behind.

I finally figured it out. How do you get an arbitrary length of data no matter what in python over sockets?

The problem is this. Suppose you have a connected socket between two machines A and B.

Suppose A does socketA.sendall(<some long string>). Now how does B recv all the data.

If B does socketB.recv(1024) its going to possibly get the first packet that was sent. B does not know how long it has to wait or how much data there is. The simplest solution is for A to attach the length of the data as in socketA.sendall(str(len(<data>)) + <data>)

A better way, ladies and gentlemen (Yes, this seemingly obvious bit of code finally struck after 4 years of programming in python) and it is applicable across any language

def getDataFromSocket(sck):
data = “”
sck.settimeout(None)
data = sck.recv(1024)
sck.settimeout(2)

while 1:
line = “”
try:
line = sck.recv(1024)
except socket.timeout:
break

if line == “”:
break

data += line
return data

 

Yes. You may all thank me now.

Advertisement