Build a UDP Server with Swoole in PHP – Step‑by‑Step Guide
This tutorial demonstrates how to create a UDP server using Swoole\Server in PHP, explains the key code components, shows how to test the server with netcat, and clarifies the role of clientInfo and the sendto method for handling incoming packets.
Swoole\Server provides a simple way to build high‑performance UDP servers in PHP. The example creates a server that listens on 127.0.0.1:9502 using the SWOOLE_SOCK_UDP socket type.
<?php
// Create a Server object listening on 127.0.0.1:9502 with UDP socket
$serv = new Swoole\Server("127.0.0.1", 9502, SWOOLE_PROCESS, SWOOLE_SOCK_UDP);
// Register the packet‑receive event handler
$serv->on('Packet', function ($serv, $data, $clientInfo) {
// Send a response back to the client
$serv->sendto($clientInfo['address'], $clientInfo['port'], "Server " . $data);
// Dump client information for debugging
var_dump($clientInfo);
});
// Start the server
$serv->start();The $clientInfo variable is an associative array containing the client’s IP address ( 'address') and port ( 'port'). Inside the on('Packet') callback, the sendto method is used to send data back to the client.
Running the Server
Save the code above as udp_server.php and start it from the command line: php udp_server.php After the server starts, you can verify that it is listening on port 9502 with tools such as netstat.
Testing with Netcat
Because UDP is connection‑less, a client can send packets directly without a prior connect. Use netcat (or nc) to send a test message:
netcat -u 127.0.0.1 9502
hello ServerThe server will echo back the received data prefixed with "Server ". The callback also prints the $clientInfo array, allowing you to see the client’s address and port.
$clientInfo holds the client’s IP and port information.
Use $serv->sendto to reply to a specific UDP client.
This example illustrates the essential steps for building, running, and testing a UDP server with Swoole, which can be extended for more complex networking scenarios.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
