Home > Article > Backend Development > How to create a UDP server with swoole (code example)
The content of this article is about the method (code example) of swoole to create a UDP server. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. help.
udp_server.php
<?php // 创建Server对象,监听 127.0.0.1:9502端口,类型为SWOOLE_SOCK_UDP $serv = new swoole_server('127.0.0.1', 9502, SWOOLE_PROCESS, SWOOLE_SOCK_UDP); // 监听数据接收事件 $serv->on('Packet', function ($serv, $data, $clientInfo) { $serv->sendto($clientInfo['address'], $clientInfo['port'], 'Server ' . $data); var_dump($clientInfo); }); // 启动服务器 $serv->start();
The UDP server has no concept of connection. After startup, the client does not need to connect and can directly send data packets to the port monitored by the server. $clientInfo is client-related information
1. Start the service
$ /usr/local/php/bin/php udp_server.php
2. After successful startup, check netstat
$ ps aux | grep php oosten 22944 0.0 2.2 314416 23220 pts/4 Sl+ 10:49 0:00 /usr/local/php/bin/php udp_server.php oosten 22945 0.0 0.4 240032 4084 pts/4 S+ 10:49 0:00 /usr/local/php/bin/php udp_server.php oosten 22947 0.0 0.7 244732 7148 pts/4 S+ 10:49 0:00 /usr/local/php/bin/php udp_server.php
3.nc connect to the server
$ nc -u 127.0.0.1 9502 ###-u,使用udp传输协议hello Server hello
4. After the client sends the data packet, the server prints the $clientInfo data
array(4) { ["server_socket"]=> int(3) ["server_port"]=> int(9502) ["address"]=> string(9) "127.0.0.1" ["port"]=> int(40635) }
5. End the process
kill 22944
The above is the detailed content of How to create a UDP server with swoole (code example). For more information, please follow other related articles on the PHP Chinese website!