Welcome, guest | Sign In | My Account | Store | Cart

An issue with socket.recv is how to know when you are done receiving data. A TCP stream guarantees the bytes will not arrive out of order or be sent more than once. But you do not know the size of the data that will be sent to you. 100 bytes could be sent as group of 10 bytes or maybe in one shot. Ultimately, this means you have to use a loop in some fashion until you know it is done.

The basic recv returns an empty string when the socket is disconnected. From that you can build a simple loop that will work as long as the sender manages to disconnect the socket at the appropriate time. However, there could be situations where a local error will mask as a clean shutdown or maybe a close() is never called.

Three very basic methods are shown below that try to fix that problem. They use either a time-based, end marker, or size of payload method. Since you cannot be sure just what you are going to receive, you have to be careful that you get enough of a message to determine the size of payload or end marker.

I updated the recv_size method to allocate data in larger chunks if it gets a large stream of data, which can increase performance.

Python, 106 lines
  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
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
import socket,struct,sys,time

Port=2222

#assume a socket disconnect (data returned is empty string) means  all data was #done being sent.
def recv_basic(the_socket):
    total_data=[]
    while True:
        data = the_socket.recv(8192)
        if not data: break
        total_data.append(data)
    return ''.join(total_data)
    
def recv_timeout(the_socket,timeout=2):
    the_socket.setblocking(0)
    total_data=[];data='';begin=time.time()
    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
        try:
            data=the_socket.recv(8192)
            if data:
                total_data.append(data)
                begin=time.time()
            else:
                time.sleep(0.1)
        except:
            pass
    return ''.join(total_data)

End='something useable as an end marker'
def recv_end(the_socket):
    total_data=[];data=''
    while True:
            data=the_socket.recv(8192)
            if End in data:
                total_data.append(data[:data.find(End)])
                break
            total_data.append(data)
            if len(total_data)>1:
                #check if end_of_data was split
                last_pair=total_data[-2]+total_data[-1]
                if End in last_pair:
                    total_data[-2]=last_pair[:last_pair.find(End)]
                    total_data.pop()
                    break
    return ''.join(total_data)

def recv_size(the_socket):
    #data length is packed into 4 bytes
    total_len=0;total_data=[];size=sys.maxint
    size_data=sock_data='';recv_size=8192
    while total_len<size:
        sock_data=the_socket.recv(recv_size)
        if not total_data:
            if len(sock_data)>4:
                size_data+=sock_data
                size=struct.unpack('>i', size_data[:4])[0]
                recv_size=size
                if recv_size>524288:recv_size=524288
                total_data.append(size_data[4:])
            else:
                size_data+=sock_data
        else:
            total_data.append(sock_data)
        total_len=sum([len(i) for i in total_data ])
    return ''.join(total_data)


##############
def start_server(recv_type=''):
    sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    sock.bind(('',Port))
    sock.listen(5)
    print 'started on',Port
    while True:
        newsock,address=sock.accept()
        print 'connected'
        if recv_type=='size': result=recv_size(newsock)
        elif recv_type=='end': result=recv_end(newsock)
        elif recv_type=='timeout': result=recv_timeout(newsock)
        else: result=newsock.recv(8192) 
        print 'got',result


if __name__=='__main__':
    #start_server()
    #start_server(recv_type='size')
    #start_server(recv_type='timeout')
    start_server(recv_type='end')

def send_size(data):
    sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    sock.connect(('localhost',Port))
    sock.sendall(struct.pack('>i', len(data))+data)
    sock.close()

def send_end(data):
    sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    sock.connect(('localhost',Port))
    sock.sendall(data+End)
    sock.close()

I employ a trivial server, to keep this as simple as possible. Just uncomment the type of receiving server you want to use to see the recv type chosen in action.

The recv_timeout function, which uses non-blocking sockets, will continue trying to get data as long as the client manages to even send a single byte. This is useful for moving data which you know very little about (like encrypted data), so cannot check for completion in a sane way.

The recv_end function tacks on an end marker understood by both the client and the server. One problem with this is that data cannot look like the marker.

The recv_size function looks for the size of the payload to be prepended to the data. I use a fixed length, 4 bytes. So then I know to always look for that. It is packed to allow a terse representation that can fit sys.maxint. This avoids the problem of data looking like the marker, however, even if it means a lot of data, you are limited w/the payload being the maximum number that can be packed. An interesting advantage of this method is that it can allocate data in larger chunks since it knows this size of the data ahead of time. For large streams of data, I saw it increase performace by 10 times.

To test this, in a another process, try using the functions that match with the server type.

send_size(data) #for recv_size send_end(data) #for recv_end

sock.sendall(data) #for timeout or simple recv(8192)

do not forget to close if you do a raw sendall

sock.close()

4 comments

Qi Peng 12 years, 7 months ago  # | flag

For the recv_size() method, the client can not send messages too quickly, at least 0.1s interval between two messages. Otherwise the later message will be lost.

e.g.

socket.send(struct.pack('>i', len('hello')) + 'hello') socket.send(struct.pack('>i', len('how are you?')) + 'how are you?')

the second message 'bey' will be lost.

socket.send(struct.pack('>i', len('hello')) + 'hello') time.sleep(0.1) socket.send(struct.pack('>i', len('how are you?')) + 'how are you?')

George Paci 11 years, 3 months ago  # | flag

The recv_end code has a bug:

If one recv() returns 'something useable ', and the next recv() returns 'as an ', and the third recv() returns 'end marker', the marker will not be recognized.

Changing End to a single character (e.g. '\n' or '\0') would fix this.

Another problem: recv_end should maintain a buffer across calls, so you don't end up throwing out the beginning of the next message.

wim 11 years, 2 months ago  # | flag

I don't like to see bare except: clauses. It should at the very least be except socket.error:

Peter Majko 7 years, 4 months ago  # | flag

Line 60 should be: if len(sock_data) > 4 or len(size_data) > 4:. This way you make sure that data will be captured even if client is sending in the chunks lesser than 4.