4
votes

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?

2
try using recv rather than recvfrom - Michael Aquilina

2 Answers

6
votes

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.

4
votes

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.