UDP server socket
suggest changeA UDP (user datagram protocol) server, unlike TCP, is not stream-based. It is packet-based, i.e. a client sends data in units called “packets” to the server, and the server identifies clients by their address. There is no built-in function that relates different packets sent from the same client (unlike TCP, where data from the same client are handled by a specific resource created by socket_accept). It can be thought of as a new TCP connection being accepted and closed every time a UDP packet arrives.
Creating a UDP server socket
$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
Binding a socket to an address
The parameters are the same as those for a TCP server. onSocketFailure() is the helper in Handling socket errors.
socket_bind($socket, "0.0.0.0", 9000) or onSocketFailure("Failed to bind to 0.0.0.0:9000", $socket);
Sending a packet
This line sends $data in a UDP packet to $address:$port.
socket_sendto($socket, $data, strlen($data), 0, $address, $port);
Receiving a packet
The following snippet attempts to manage UDP packets in a client-indexed manner.
$clients = [];
while (true){
socket_recvfrom($socket, $buffer, 32768, 0, $ip, $port) !== false
or onSocketFailure("Failed to receive packet", $socket);
$address = "$ip:$port";
if (!isset($clients[$address])) $clients[$address] = new Client();
$clients[$address]->handlePacket($buffer);
}
Closing the server
socket_close can be used on the UDP server socket. Since PHP 8, socket_create() returns a Socket object, not a resource. Closing it frees the UDP address, allowing other processes to bind to this address.