Home > Blockchain >  How asyncio UDP connection receives whole datagrams?
How asyncio UDP connection receives whole datagrams?

Time:04-12

There is an interface asyncio.DatagramProtocol from Python library. It gives possibility to implement receiving datagrams by using method datagram_received(self, data, addr):

class MyDatagramProtocol(asyncio.DatagramProtocol):
    def datagram_received(self, data: bytes, addr: tuple[str, int]):
        # Here I can use data as whole datagram. 
        # If there are more pending datagrams, it will called more than once
        pass

The asyncio eventloop receives whole datagrams. But when I use BSD socket, I should use all or part of received data. Total data can be greater than one datagram. And I don't know the bounds of this data. I just can parse it by using of my own algorithms (read heading, count of bytes in body, etc).

if (ioctlsocket(Socket, FIONREAD, (u_long*)(&PendingDataSize)) == 0)
{
    BytesRead = recv(Socket, (char*)Data, PendingDataSize, Flags); 
    // Now I can use Data and parse it here. 
    // But Data can be two or more datagrams if remote machine sent two or more packets?
}

How can I repeat the behavior of asyncio but with just BSD sockets?

CodePudding user response:

With a datagram socket, recv always receives only one datagram at a time.

See man page udp(7):

All receive operations return only one packet.

  • Related