A 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 client identifies clients by their address. There is no builtin 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 as a new TCP connection is accepted and closed every time a UDP packet arrives.
$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
The parameters are same as that for a TCP server.
socket_bind($socket, "0.0.0.0", 9000) or onSocketFailure("Failed to bind to 0.0.0.0:9000", $socket);
This line sends $data
in a UDP packet to $address
:$port
.
socket_sendto($socket, $data, strlen($data), 0, $address, $port);
The following snippet attempts to manage UDP packets in a client-indexed manner.
$clients = [];
while (true){
socket_recvfrom($socket, $buffer, 32768, 0, $ip, $port) === true
or onSocketFailure("Failed to receive packet", $socket);
$address = "$ip:$port";
if (!isset($clients[$address])) $clients[$address] = new Client();
$clients[$address]->handlePacket($buffer);
}
socket_close
can be used on the UDP server socket resource. This will free the UDP address, allowing other processes to bind to this address.