MOCKSTACKS
EN
Questions And Answers

More Tutorials









PHP UDP server socket


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

Conclusion

In this page (written and validated by ) you learned about PHP UDP server socket . What's Next? If you are interested in completing PHP tutorial, your next topic will be learning about: PHP MySQLi.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.