24、Hyperf 3 快速使用 - Hyperf 3 TCP 服务

作者: 温新

分类: 【Hyperf 3 基础系列】

阅读: 409

时间: 2023-04-25 15:59:41

hi,我是温新,一名 PHPer

Hypref 版本:Hyperf 3.0

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

关于 TCP 服务,官方文档没有特别详细的说明。再使用 Hyperf 3 的 TCP 服务时,想想 Swoole TCP 服务有哪些要做事的。本篇文章将需要注意的点用注释形式说明 。

下面开始演示。

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

<?php
// config/autoload/server.php    
'servers' => [
    // TCP 服务配置
    [
        // 服务名称
        'name'      => 'tcp',
        // 服务类型
        'type'      => Server::SERVER_BASE,
        // 服务 ID
        'host'      => '0.0.0.0',
        // 端口
        'port'      => 9504,
        // 指定 TCP 服务
        'sock_type' => SWOOLE_SOCK_TCP,
        'callbacks' => [
            // 监听连接(可选)
            Event::ON_CONNECT => [\App\Controller\Server\TcpServerController::class, 'onConnect'],
            // 监听消息事件必须配置(控制器中必须实现)
            Event::ON_RECEIVE => [\App\Controller\Server\TcpServerController::class, 'onReceive'],
            // 监听关闭(可选)
            Event::ON_CLOSE   => [\App\Controller\Server\TcpServerController::class, 'onClose'],
        ],
        // 服务参数配置
        'settings'  => [
            // 按需要配置
        ]
    ],
],

注意点:

1、如果在配置文件中监听了相关事件,那么在控制器中必须实现该方法。如,在配置文件中配置了 onConnect 事件,那么在控制器必须实现;

2、如果在控制器中实现了 onConnect 监听,但是没有在配置文件中配置,那么该事件不生效,也不会报错。

第二步:创建 TCP 服务类

<?php
// App\Controller\Server\TcpServerController.php

namespace App\Controller\Server;

use Hyperf\Contract\OnReceiveInterface;

// 实现接收消息接口
class TcpServerController implements OnReceiveInterface
{
    // 监听客户端连接
    public function onConnect($server, int $fd)
    {
        echo '客户端连接: ' . $fd . PHP_EOL;
    }

    // 监听接收消息
    public function onReceive($server, int $fd, int $reactorId, string $data): void
    {
        echo $fd . PHP_EOL;
        $server->send($fd, '来自服务端的消息:' . $data);
    }

    // 监听关闭事件
    public function onClose($server, int $fd)
    {
        echo $fd . ' 断开连接' . PHP_EOL;
    }
}

第三步:启动服务

php bin/hyperf start

第四步:客户端连接

这里使用 telnet 进行连接。

$ telnet 192.168.31.90 9504
Trying 192.168.31.90...
Connected to 192.168.31.90.
Escape character is '^]'.
^]
telnet> 
PHP
来自服务端的消息:PHP
Laravel
来自服务端的消息:Laravel
Hyperf
来自服务端的消息:Hyperf

第五步:使用 Swoole\Client 连接

现在我们编写 Swoole\Client 服务,然后和服务端进行连接。该客户端文件位置随便在哪都行。

<?php
// hyperf-swoole-client.php
$client = new Swoole\Client(SWOOLE_SOCK_TCP);
$client->connect('192.168.31.90', 9504);
$client->send('swoole cline: hello hyperf 3');
echo $client->recv() . PHP_EOL;

输出结果:

$ php hyperf-swoole-client.php 
来自服务端的消息:swoole cline: hello hyperf 3

TCP 服务到这里已经完成。

我是温新,下篇文章 Hyperf3 UDP 服务。

请登录后再评论