Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to continuously read data from socket in python?

Tags:

python

sockets

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?

like image 794
Kin Avatar asked Dec 25 '22 10:12

Kin


1 Answers

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.

like image 172
Michael Aquilina Avatar answered Jan 05 '23 20:01

Michael Aquilina