Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

From the analysis, I concluded that in the following three cases the socket.recv(recv_size) will return.

After the connection was closed. For example, the client-side called socket.close() or any socket error occurred, it would return an empty string.

Some information comes, the size of data is more than recv_size.

For some record, the size of data is less than recv_size and no more data come after a short time (I found 0.1s would work).

More details about #3:

#server.py

while True:

    data = sock.recv(10)

    print data, 'EOF'

#client1.py

sock.sendall("12345")

sock.sendall("a" * 50)

#client2.py

sock.sendall("12345")

time.sleep(0.1)

sock.sendall("a" * 50)

#When I run client1.py, the server.py echos:

12345aaaaa EOF

aaaaaaaaaa EOF

aaaaaaaaaa EOF

aaaaaaaaaa EOF

aaaaaaaaaa EOF

aaaaa EOF

#When I run client2.py, the server.py echos:

12345 EOF

aaaaaaaaaa EOF

aaaaaaaaaa EOF

aaaaaaaaaa EOF

aaaaaaaaaa EOF

aaaaaaaaaa EOF

Are my conclusions correct? 

1 Answer

0 votes
by (108k points)

Yes, your judgment is correct. socket.recv is a blocking signal.

socket.recv(1024) will read at utmost 1024 bytes, blocking if no information is waiting to be read. If you don't gather all data, another call to socket.recv won't block.

It will also end with a blank string if the connection is closed or there is an error. If you want a non-blocking socket, you can use the select module or you can use socket.setblocking.

Do you want to learn Python more? Please check out the Python video tutorial given below:

Related questions

0 votes
1 answer
0 votes
1 answer
asked Jan 19, 2021 in Python by ashely (50.2k points)
0 votes
2 answers
0 votes
1 answer

Browse Categories

...