4

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?

1
  • try using recv rather than recvfrom Commented Apr 15, 2014 at 10:14

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

3 Comments

still the same, only first 1024
also, try using recv rather than recvfrom
mmm, yea, sorry, the problem solved with Exceptions and setblocking
4

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.

Comments

Your Answer

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.