mainServerCreate 中创建下面的方法。

# 1. 子服务

protected static function registerTcp($register)
{
    $server  = \EasySwoole\EasySwoole\ServerManager::getInstance()->getSwooleServer();
    $subPort = $server->addlistener("0.0.0.0", 9502, SWOOLE_TCP);
    $subPort->set([
        'reactor_num'              => 2,     // reactor thread num
        'worker_num'               => 4,     // worker process num
        'backlog'                  => 128,   // listen backlog
        'package_max_length'       => 81920,
        'heartbeat_idle_time'      => 600,    // 表示一个连接如果600秒内未向服务器发送任何数据,此连接将被强制关闭
        'heartbeat_check_interval' => 60,     // 表示每60秒遍历一次
        'open_eof_check'           => true,
        'open_eof_split'           => true,
        'package_eof'              => '$$',
    ]);

    //创建一个 Dispatcher 配置
    $conf = new \EasySwoole\Socket\Config();
    //设置Dispatcher为Tcp 模式
    $conf->setType(\EasySwoole\Socket\Config::TCP);

    $dispatch = null;
    try {
        $conf->setParser(new TcpParser());      //设置解析器对象
        $dispatch = new Dispatcher($conf);      //创建Dispatcher对象并注入config对象
    } catch (\Exception $e) {
    }

    //创建一个 Dispatcher 配置
    $subPort->on(EventRegister::onConnect, function (\Swoole\Server $server, int $fd, int $reactor_id) {
        echo "fd {$fd} connected";
    });

    $subPort->on(EventRegister::onReceive, function (\Swoole\Server $server, int $fd, int $reactor_id, string $data) use ($dispatch) {
        $dispatch->dispatch($server, $data, $fd, $reactor_id);
    });

    $subPort->on(EventRegister::onClose, function (\Swoole\Server $server, int $fd, int $reactor_id) {
        echo "fd {$fd} closed";
    });
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

# 2. TCP解析器

<?php

namespace App\Tcp;

use EasySwoole\Socket\AbstractInterface\ParserInterface;
use EasySwoole\Socket\Bean\Caller;
use EasySwoole\Socket\Bean\Response;
use EasySwoole\Socket\Client\Tcp as TcpClient;

class TcpParser implements ParserInterface
{
    /**
     * 解码上来的消息
     * @param string $raw 消息内容
     * @param TcpClient $client
     * @return Caller|null
     */
    public function decode($raw, $client): ?Caller
    {
        $caller = new Caller;
        if ($raw !== 'PING') {
            $payload         = json_decode($raw, true);
            $class           = isset($payload['controller']) ? $payload['controller'] : 'CodePay';
            $action          = isset($payload['action']) ? $payload['action'] : 'index';
            $params          = isset($payload) ? (array)$payload : [];
            $controllerClass = "\\App\\Tcp\\Controller\\" . ucfirst($class);
            if (!class_exists($controllerClass)) $controllerClass = "\\App\\Tcp\\Controller\\CodePay";
            $caller->setClient($client);
            $caller->setControllerClass($controllerClass);
            $caller->setAction($action);
            $caller->setArgs($params);
        } else {
            // 设置心跳执行的类和方法
            $caller->setControllerClass(\App\Tcp\Controller\CodePay::class);
            $caller->setAction('heartbeat');
        }
        return $caller;
    }

    /**
     * 打包下发的消息
     * @param Response $response 控制器返回的响应
     * @param TcpClient $client
     * @return string|null
     */
    public function encode(Response $response, $client): ?string
    {
        return $response->getMessage();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

# 3. 业务

<?php

namespace App\Tcp\Controller;

class CodePay extends Base
{

    public function pay()
    {
        $fd   = $this->caller()->getClient()->getFd(); // 请求用户的fd
        $data = $this->caller()->getArgs();            // 获取请求参数
        $data['code']     = 0;
        $data['deviceNo'] = $data['deviceNo'];
        $data['body']     = null;
        $this->response()->setMessage(json_encode($data).'$$');
    }

    public function heartbeat()
    {
        $data['code'] = 0;
        $this->response()->setMessage(json_encode($data)); // 推送消息
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24