1:创建服务端文件UDP.php
<?php class UDP { private $server = null; public function __construct(){ $this -> server = new Swoole\Server('127.0.0.1', 9502, SWOOLE_PROCESS, SWOOLE_SOCK_UDP); //监听数据接收事件 $this -> server->on('Packet', [$this,"onPacket"]); //启动服务器 $this -> server->start(); } public function onPacket($server, $data, $clientInfo){ var_dump($clientInfo); $server->sendto($clientInfo['address'], $clientInfo['port'], "Server:{$data}"); } } new UDP();
2:创建客户端文件UDP.php
<?php // use Swoole\Coroutine\Client; // use function Swoole\Coroutine\run; go(function () { $client = new Swoole\Coroutine\Client(SWOOLE_SOCK_UDP); if (!$client->connect('127.0.0.1', 9502, 0.5)) { echo "connect failed. Error: {$client->errCode}\n"; } // fwrite(STDOUT,"请输入:"); // $res = fgetc(STDIN); // $client->send($res); $client->send("你好!"); echo $client->recv(); $client->close(); });
UDP链接已完成