Python Novice
Python Novice

Reputation: 2200

Receive all of the data when using python socket

I am using socket to connect to a simple server to receive some data:

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host = "X.X.X.X"
port = Y
s.connect((host,port))

data = s.recv(512)
print data

Not all of the expected received data is received; some of it is cut off. So any operations that I need to perform on the received data is thrown off.

I've tried using s.settimeout(1) and putting the socket in non-blocking mode. Strangely, it works just fine in ipython.

Upvotes: 0

Views: 5637

Answers (1)

superjedi
superjedi

Reputation: 524

Even if 512 bytes are sent from the server to the client, if they're sent through multiple packets, and that one packet has TCP Push flag set, the kernel will stop buffering and hand over the data to userland, ie, your application.

You should loop on data = s.recv(512) and print data. I'd even remove the '512', which is useless.

while True:
    if not data: break
    data = s.recv()
    print data

Upvotes: 1

Related Questions