Recv Over Sockets in Python

By oBelIX

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.

11 Responses to “Recv Over Sockets in Python”

  1. mythalez Says:

    shouldn’t python by definition be pretty long by itself ??? :P

  2. General Bordeaux Says:

    you still use python :-O i think you should be using something like “visual” python by this time :P anyway thanks for the script :)

  3. Maruti Borker Says:

    :P

  4. Sreejith Says:

    sucketh programming :P

  5. obelix Says:

    @mythalez and sreejith: very droll …

    @bordeaux: python rocks, its used everywhere

  6. General Bordeaux Says:

    @obelix
    i know python rocks … but you should have made it visual by this time .. you are in m$ since one long year :P

  7. Sreejith Says:

    was reminded of this post as i read this.. http://xkcd.com/353/

  8. Python on .NET Says:

    http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython

  9. HalleY Says:

    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 :D

  10. ikex Says:

    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]

  11. cocobear Says:

    I think it’s a bit slowly.
    every time we should wait 2s.

Leave a Reply