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:
breakif line == “”:
breakdata += line
return data
Yes. You may all thank me now.
December 1, 2007 at 10:45 am |
shouldn’t python by definition be pretty long by itself ???
December 2, 2007 at 1:41 am |
you still use python :-O i think you should be using something like “visual” python by this time
anyway thanks for the script
December 2, 2007 at 2:18 am |
December 3, 2007 at 2:11 am |
sucketh programming
December 3, 2007 at 9:02 am |
@mythalez and sreejith: very droll …
@bordeaux: python rocks, its used everywhere
December 3, 2007 at 11:23 pm |
@obelix
i know python rocks … but you should have made it visual by this time .. you are in m$ since one long year
December 7, 2007 at 1:37 am |
was reminded of this post as i read this.. http://xkcd.com/353/
December 9, 2007 at 12:21 pm |
http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython
December 12, 2007 at 3:30 pm |
I think the socket.timeout should be replaced by socket.dynmulpath .. stands for an automated timedout due to asynchronous dynamic multipathing owing to some packet switching by djikstra’s second theorem .
PS : Post the 10H type posts not these techie posts
August 27, 2008 at 7:56 am |
Sorry to resurrect an old blog post but you could just end the data with “\n”
and read 1by1 until the end
[CODE]
dat = “”
while 1:
char = self.sock.recv(1)
if char == “\n”: return dat
else: dat=dat+char
[/CODE]
February 19, 2009 at 11:42 am |
I think it’s a bit slowly.
every time we should wait 2s.