UDP server socket

suggest change

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.

Creating a UDP server socket

$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);

Binding a socket to an address

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);

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) === true
            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 resource. This will free the UDP address, allowing other processes to bind to this address.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents