53 lines
1.3 KiB
PHP
53 lines
1.3 KiB
PHP
<?php
|
||
/**
|
||
* UDP服务端类
|
||
* User: fantasticbin
|
||
* Date: 2020/1/15
|
||
*/
|
||
class Udp
|
||
{
|
||
const HOST = '127.0.0.1';
|
||
const PORT = 9502;
|
||
const WORKER_NUM = 2;
|
||
const MAX_REQUEST = 10000;
|
||
|
||
public $server = null;
|
||
|
||
public function __construct()
|
||
{
|
||
// 创建UDP服务器,第四个参数指定为UDP,监听 127.0.0.1:9502 端口
|
||
$this->server = new Swoole\Server(self::HOST, self::PORT, SWOOLE_PROCESS, SWOOLE_SOCK_UDP);
|
||
|
||
// 设置TCP服务器参数
|
||
$this->server->set([
|
||
'worker_num' => self::WORKER_NUM,
|
||
'max_request' => self::MAX_REQUEST
|
||
]);
|
||
|
||
// 监听数据接收事件
|
||
$this->server->on('Packet', [$this, 'onPacket']);
|
||
}
|
||
|
||
/**
|
||
* 监听数据接收事件
|
||
* @param $serv Swoole\Server UDP对象
|
||
* @param $data string 客户端传入的字符串
|
||
* @param $clientInfo array 客户端信息数据
|
||
*/
|
||
public function onPacket($serv, $data, $clientInfo)
|
||
{
|
||
$serv->sendto($clientInfo['address'], $clientInfo['port'], 'Hello ' . $data . '!' . PHP_EOL);
|
||
var_dump($clientInfo);
|
||
}
|
||
|
||
/**
|
||
* 启动UDP服务器
|
||
*/
|
||
public function start()
|
||
{
|
||
$this->server->start();
|
||
}
|
||
}
|
||
|
||
$udp = new Udp();
|
||
$udp->start(); |