1

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()
asked Mar 9, 2017 at 12:42

1 Answer 1

2

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...

answered Mar 9, 2017 at 12:48
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.