目录

示例代码 - UDP

优质
小牛编辑
136浏览
2023-12-01

与监听TCP命令同理,在服务启动前事件中添加事件监听。

  1. use CoreComponentSocketClientUdpClient;
  2. function beforeWorkerStart(swoole_server $server){
  3. $udp = $server->addlistener("0.0.0.0",9503,SWOOLE_UDP);
  4. //udp 请勿用receive事件,除非设置eof
  5. $udp->on('packet',function(swoole_server $server, $data,$clientInfo){
  6. var_dump($data);
  7. $client = new UdpClient($clientInfo);
  8. $server->sendto($client->getAddress(),$client->getPort(),'hello');
  9. });
  10. }

测试代码

  1. $client = new swoole_client(SWOOLE_SOCK_UDP);
  2. if (!$client->connect('127.0.0.1', 9503, -1))
  3. {
  4. exit("connect failed. Error: {$client->errCode}n");
  5. }
  6. $client->send("hellon");
  7. echo $client->recv();
  8. $client->close();