[Webman] 如何创建TCP服务器

390 阅读1分钟
1.编写RPC进程 (这里是事件的编写的地方)

新建文件 process/Rpc.php

<?php
namespace process;
use Workerman\Connection\TcpConnection;
class Rpc
{
    /**
     * 注意: 控制器不在这里, 而是前端传的Class指定的, 测试是在service/User
     */
    public function onMessage(TcpConnection $connection, $data)
    {
        static $instances = [];
        $data = json_decode($data, true);
        $class = 'service\\'.$data['class'];
        $method = $data['method'];
        $args = $data['args'];
        if (!isset($instances[$class])) {
            $instances[$class] = new $class; // 缓存类实例,避免重复初始化
        }
        $connection->send(call_user_func_array([$instances[$class], $method], $args));
    }
}
2.打开 config/process.php 增加配置启动rpc进程
<?php
use Workerman\Worker;

return [
    // File update detection and automatic reload -- 这个是原来的
    'monitor' => [
        // 省略
    ],
    
    // 新增的RPC进程
    'rpc'  => [
        'handler' => process\Rpc::class,
        'listen'  => 'text://0.0.0.0:8888', // 这里用了text协议,也可以用frame或其它协议
        'count'   => 8, // 可以设置多进程
    ]

];
3.新建service目录,创建 service/User.php 服务, 这里是业务代码编写的地方
<?php
namespace service;
class User
{
    public function get($uid)
    {
        return json_encode([
            'uid'  => $uid,
            'name' => 'tom',
            'time'  => date("Y-m-d H:i:s")
        ]);
    }
}
4.重启webman php start.php restart
5.客户端调用(估计放在window也可以)

创建client.php, 执行php -f client.php

<?php
$client = stream_socket_client('tcp://127.0.0.1:8888');
$request = [
    'class'   => 'User', //指定访问哪个服务 service/User
    'method'  => 'get',
    'args'    => [100], // 100 是 $uid
];
fwrite($client, json_encode($request)."\n"); // text协议末尾有个换行符"\n"
$result = fgets($client, 10240000);
$result = json_decode($result, true);
var_export($result);