Ethan
Ethan

Reputation: 313

Python: why recv() didn't block in blocking mode?

here is my code, the client should be blocking in recv (it expect 256 characters), cause the server just send 5 character to it, but recv return, any idea?

#-----------------------------------------------------------
# server.py
import socket
import sys

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('localhost', 10000))
sock.listen(1)

while True:
    connection, client_address = sock.accept()
    try:
        connection.send('hello'.encode('utf-8'))
    except Exception:
        connection.close()

#-----------------------------------------------------------
# client.py
import socket
import sys

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', 10000))
sock.setblocking(True)
try:
    data = sock.recv(256)
    print('received "%s"' % data.decode('utf-8'))

finally:
    sock.close()

Upvotes: 1

Views: 3363

Answers (1)

mguijarr
mguijarr

Reputation: 7908

sock.recv() returns because something was received on the socket, or if len(data) is 0, because the server closed the connection.

Expecting 256 bytes do not mean they will be received in one go. In your example, 256 is the maximum number of bytes.

The blocking behavior means: wait until something is received, not to wait until all that is expected is received.

If you are sure your server will send 256 bytes you can make a loop:

data = ''
while len(data) < 256:
  data += socket.recv(256)

If you cannot receive 256 bytes in one go, it means your network is maybe quite unstable (wifi ?) or the server or your client runs on an embedded platform with very small buffers ? Or the server is sending small chunks...

Upvotes: 2

Related Questions