UDPServer类 app/Server/UdpServer.php
<?php
declare(strict_types=1);
namespace App\Server;
use Hyperf\Contract\OnPacketInterface;
class UdpServer implements OnPacketInterface
{
//监听数据接收事件
public function onPacket($server, $data, $clientInfo): void
{
var_dump($clientInfo);
$server->sendto($clientInfo['address'], $clientInfo['port'], 'Server:' . $data);
}
}
UDP服务配置 config/autoload/server.php
<?php
declare(strict_types=1);
use Hyperf\Server\Event;
use Hyperf\Server\Server;
use Swoole\Constant;
return [
'mode' => SWOOLE_PROCESS,
'servers' => [
[
'name' => 'http',
'type' => Server::SERVER_HTTP,
'host' => '0.0.0.0',
'port' => 9501,
'sock_type' => SWOOLE_SOCK_TCP,
'callbacks' => [
Event::ON_REQUEST => [Hyperf\HttpServer\Server::class, 'onRequest'],
],
],
//UDP服务配置
[
'name' => 'udp',
'type' => Server::SERVER_BASE,
'host' => '0.0.0.0',
'port' => 9504,
'sock_type' => SWOOLE_SOCK_UDP,
'callbacks' => [
Event::ON_PACKET => [App\Server\UdpServer::class, 'onPacket'],
],
'settings' => [
// 按需配置
],
],
],
'settings' => [
Constant::OPTION_ENABLE_COROUTINE => true,
Constant::OPTION_WORKER_NUM => swoole_cpu_num(),
Constant::OPTION_PID_FILE => BASE_PATH . '/runtime/hyperf.pid',
Constant::OPTION_OPEN_TCP_NODELAY => true,
Constant::OPTION_MAX_COROUTINE => 100000,
Constant::OPTION_OPEN_HTTP2_PROTOCOL => true,
Constant::OPTION_MAX_REQUEST => 100000,
Constant::OPTION_SOCKET_BUFFER_SIZE => 2 * 1024 * 1024,
Constant::OPTION_BUFFER_OUTPUT_SIZE => 2 * 1024 * 1024,
// Task Worker 数量,根据您的服务器配置而配置适当的数量
'task_worker_num' => 2,
// 因为 `Task` 主要处理无法协程化的方法,所以这里推荐设为 `false`,避免协程下出现数据混淆的情况
'task_enable_coroutine' => false,
],
'callbacks' => [
Event::ON_WORKER_START => [Hyperf\Framework\Bootstrap\WorkerStartCallback::class, 'onWorkerStart'],
Event::ON_PIPE_MESSAGE => [Hyperf\Framework\Bootstrap\PipeMessageCallback::class, 'onPipeMessage'],
Event::ON_WORKER_EXIT => [Hyperf\Framework\Bootstrap\WorkerExitCallback::class, 'onWorkerExit'],
// Task callbacks
Event::ON_TASK => [Hyperf\Framework\Bootstrap\TaskCallback::class, 'onTask'],
Event::ON_FINISH => [Hyperf\Framework\Bootstrap\FinishCallback::class, 'onFinish'],
],
];
客户端测试
huyongjians-MacBook-Pro:WWW huyongjian$ netcat -u 118.195.173.53 9504
huyongjian
Server:huyongjian
服务端打印
array(5) {
["server_socket"]=>
int(9)
["dispatch_time"]=>
float(1633597813.6695)
["server_port"]=>
int(9504)
["address"]=>
string(13) "120.235.227.6"
["port"]=>
int(4537)
}