<?php
class Udp
{
const HOST = '127.0.0.1';
const PROT = '9502';
public $udpServer = null;
public $config = [
'worker_num' => 8, // 进程数
'max_request' => 10000, // 当前 Worker 进程允许收到的最大请求次数
];
public function __construct()
{
/**
* 创建server对象 监听127.0.0.1:9502端口
* 第三个参数为 运行模式 可以填2个常量 SWOOLE_PROCESS / SWOOLE_BASE
* 第四个参数为 Server的类型
*/
$this->udpServer = new Swoole\Server(self::HOST, self::PROT, SWOOLE_PROCESS, SWOOLE_SOCK_UDP);
// 设置参数
$this->udpServer->set($this->config);
// 监听数据接收事件
$this->udpServer->on('packet', [$this, 'onPacket']);
// 启动服务
$this->udpServer->start();
}
/**
* 监听数据接收事件
* $server 服务器
* $data 客户端发送的消息
* $clientInfo 客户端的相关信息,是一个数组,有客户端的 IP 和端口等内容
*/
public function onPacket($server, $data, $clientInfo)
{
// 向客户端发送数据
$server->sendto($clientInfo['address'], $clientInfo['port'], 'Server:' . $data);
}
}
new Udp();
swoole UDP服务器
最新推荐文章于 2024-05-08 08:32:47 发布