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:


Sockets:
* UDP server socket

Table Of Contents
2 Arrays
4 Types
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR