Kin
Kin

Reputation: 4596

How to continuously read data from socket in python?

The problem is that i don't know how much bytes i will receive from socket, so i just trying to loop.

buffer = ''

while True:
    data, addr = sock.recvfrom(1024)
    buffer += data
    print buffer

As I understood recvfrom return only specified size of bytes and the discards other data, is it possible somehow continuously read this data to buffer variable?

Upvotes: 4

Views: 23303

Answers (2)

Jinhua Wang
Jinhua Wang

Reputation: 1759

I suggest using readline as the buffer and use "\n" as the separator between lines:

#read one line from the socket
def buffered_readLine(socket):
    line = ""
    while True:
        part = socket.recv(1)
        if part != "\n":
            line+=part
        elif part == "\n":
            break
    return line

This is helpful when you want to buffer without closing the socket.

sock.recv(1024) will hang when there is no data being sent unless you close the socket on the other end.

Upvotes: 4

Michael Aquilina
Michael Aquilina

Reputation: 5520

It wont discard the data, it will just return the data in the next iteration. What you are doing in your code is perfectly correct.

The only thing I would change is a clause to break the loop:

buffer = ''

while True:
    data, addr = sock.recv(1024)
    if data:
        buffer += data
        print buffer
    else:
        break

An empty string signifies the connection has been broken according to the documentation

If this code still does not work then it would be good to show us how you are setting up your socket.

Upvotes: 6

Related Questions