25、Hyperf 3 快速使用 - Hyperf 3 UDP 服务

作者: 温新

分类: 【Hyperf 3 基础系列】

阅读: 303

时间: 2023-04-25 16:00:32

hi,我是温新,一名 PHPer

Hypref 版本:Hyperf 3.0

学习目标:学习 Hyperf 3 UDP 服务

第一步:server 配置文件中添加 UDP 服务

<?php
// config/autoload/server.php    
'servers' => [
    // UDP 服务
    [
        'name'      => 'udp',
        'type'      => Server::SERVER_BASE,
        'host'      => '0.0.0.0',
        'port'      => 9508,
        'sock_type' => SWOOLE_SOCK_UDP,
        'callbacks' => [
            // 监听接收消息事件(必填)
            Event::ON_PACKET => [\App\Controller\Server\UdpServerController::class, 'onPacket'],
        ],
        'settings'  => [
            // 按需配置
        ],
    ],
],

第二步:创建 UDP 服务类

<?php
// App\Controller\Server\UdpServerController.php
    
namespace App\Controller\Server;

use Hyperf\Contract\OnPacketInterface;

// 实现 OnPacketInterface 接口
class UdpServerController implements OnPacketInterface
{
    // 监听接收数据
    public function onPacket($server, $data, $clientInfo): void
    {
        $message = '来自 UDP 服务的数据:' . $data . PHP_EOL;
        $server->sendto($clientInfo['address'], $clientInfo['port'], $message);
    }
}

$clientInfo 输出信息如下:

Array
(
    [server_socket] => 7
    [dispatch_time] => 1678787269.3639
    [server_port] => 9508
    [address] => 192.168.31.90
    [port] => 38277
)

第三步:启动服务

php bin/hyperf.php start

第四步:使用 netcat 连接服务

$ netcat -u 192.168.31.90 9508
hyperf
来自 UDP 服务的数据:hyperf

第五步:使用 Swoole\Client 连接 UDP 服务

<?php
// hyperf-swoole-udp-client.php
$client = new Swoole\Client(SWOOLE_SOCK_UDP);
if (!$client->connect('192.168.31.90', 9508, -1)) {
    exit('连接服务失败' . $client->errCode);
}

$client->send('Hi, UDP SERVER');
echo $client->recv() . PHP_EOL;

输出结果如下:

$ php hyperf-swoole-udp-client.php
来自 UDP 服务的数据:Hi, UDP SERVER

UDP 服务到这里就结束了。

我是温新,下一篇文章,Hyperf3 WebSocket。

请登录后再评论