swoole-src icon indicating copy to clipboard operation
swoole-src copied to clipboard

How to implement a greedy UDP read loop in swoole?

Open simonhf opened this issue 5 years ago • 1 comments

Hello! I managed to create a UDP server and use on packet or on receive events (What's the difference apart from the API? Only on receive allows you to access the fd?) to receive a UDP packet as expected. However, if I was writing a high performance UDP server in C then while in the network read event, I'd greedily read UDP packets until non-blocking recv() returns EAGAIN. Reading in this way is much faster than generating an event for each packet. Is there a way to do something similar for greedily reading UDP packets via swoole? Thanks, Simon

simonhf avatar Jul 11 '18 00:07 simonhf

According to Swoole's guide book: When your server is listening to both TCP and UDP protocols, onPacket only receives UDP packets and onReceive ony receives TCP data. But if onPacket listener has not been set, then all data including TCP and UDP will be caught by onReceive event.

onPacket:

the third parameter is called $client_info, which is an array including address, port and server_socket

and fd can be calculated by the following codes:

$fd = unpack('L', pack('N', ip2long($client_info['address'])))[1];

reactor_id can be calculated by the following codes:

$reactor_id = ($client_info['server_socket'] << 16) + $client_info['port'];

onReceive

you already know its parameters look like this:

onReceive(swoole_server $server, int $fd, int $reactor_id, string $data)

Greedily Reading UDP Packets

Is there any way for greedily reading UDP packets: not that I know of. I donno, that could probably be a feature in the future.

dizys avatar Jul 13 '18 17:07 dizys