Reading all data from a UDP socket

Situation:

I have a sendersocket that is mapped to the localhost 33100 UDP port. I have a receiver socket associated with the localhost 33101 UDP port.

The sender-sender sends 4500 bytes of data (the string "hello man" * 500). On the receiver side, I have an epoll object that waits for an EPOLLIN event on the receiver. When an event occurs, I do:

while True: msg_received = receiver_socket.recv(128) if msg_received.decode("UTF-8") == "": break else: print msg_received.decode("UTF-8") 

Problem:

The main problem is that I cannot read again after I read the first 128 bytes of data. The sender side says that it sent 4,500 bytes of data as expected.

If the sender again sends the same 4500 bytes of data, the EPOLLIN event is logged again and I am reading a new line. Somehow, the buffer is cleared after my first reading.

Now, although the sender just sent me 4,500 bytes of data, the first recv gives me 128 bytes of data, and then nothing recv ed after that.

Iā€™m probably doing something really stupid, so please enlighten me. I want to get all 4500 bytes of data.

+4
source share
2 answers

You should always call recv with 65535 (maximum UDP packet size) if you do not already know the packet size. Otherwise, when you call recv , the entire packet is marked as read and msg_received , but then only the first 128 bytes are passed to msg_received .

edit : when (if) you go to receive data only over the network, you can use a lower number for recv , as indicated in the Docs

+6
source

If you know that you will receive 4500 bytes of data, you can call receiver_socket.recv(4500)

What your code says is that the maximum bytes read are 128 with receiver_socket.recv(128)

See python documentation for sockets

+1
source

All Articles