[webman] 使用Webman做TCP客户端

155 阅读1分钟
1.编写进程文件, 指定处理类(有点像路由)

1.config/process.php

<?php

use Workerman\Worker;

return [
    // File update detection and automatic reload
    'monitor' => [
        // 省略
    ],

    // 自定义非监听进程(就是TCP客户端?)
    'task' => [
        'handler'  => app\TaskTest::class
    ],

];
2.创建客户端
<?php
namespace app;
use Workerman\Connection\TcpConnection;
use Workerman\Connection\AsyncTcpConnection;
use Workerman\Worker;

class TaskTest
{
    protected $ip = 'IP';
    protected $port = 8888;

    public function onWorkerStart()
    {
        echo date("Y-m-d H:i:s") . PHP_EOL;
        $client = new AsyncTcpConnection("tcp://{$this->ip}:{$this->port}");
        $client->connect();
        //var_dump($client);
        // 连接成功回调函数
        $client->onConnect = function () {
            echo "Connected to server.\n";
        };

        // 接收到服务器数据回调函数
        $client->onMessage = function ($connection, $data) {
            echo "Received data from server: $data\n";
        };

        // 连接关闭回调函数
        $client->onClose = function () {
            echo "Connection closed.\n";
        };
    }

}