Python socket stays blocked on socket.recv() when client expects data

2.1k views Asked by At

I am trying my hand at socket programming in Python and ran an issue. The code for the 'server' side is:

(connection, address) = in_socket.accept()

size_str =  connection.recv(4)
result_size=struct.unpack('>i',size_str)
string_buffer=[]
print 'results size is: ',result_size[0]
while 1:
    r = connection.recv(result_size[0])
    print 'length is: ', len(r)
    if not r:
        break

    string_buffer.append(r)
s = ''.join(string_buffer)
print 'recieved data: ', s     
connection.send('Thanks for connecting')

And for the client side, it is:

sock.connect(server_address)
message = ('{\"message\":\"This is the messcxvage\"}')
packedlen=struct.pack('>i',len(message))
sock.send(packedlen)
sock.send(message)
xyz = sock.recv(1024)

When the client is expecting data back, the if condition for breaking out of the while loop in the server is never fulfilled. The server keeps waiting to receive more data. If I comment out the last lines from both code samples, it works as expected. Why does this happen and what is the fix for this?

Thanks in advance!

1

There are 1 answers

0
Armali On

Why does this happen

You correctly answered this question in your comment.

and what is the fix for this?

Just don't program an endless loop. You wisely send the length of the data from the client to the server, so the server knows how many bytes to await. On UNIX systems dispose of the whole while 1: loop as well as the s = ''.join(string_buffer) and write only

s = connection.recv(result_size[0], socket.MSG_WAITALL)

instead. On Windows systems (not having MSG_WAITALL) you still need to loop, but only until result_size[0] bytes overall have been received.