用webman 建立tcp 的服务端
安装webman
安装 composer require webman/gateway-worker
文件:config/plugin/webman/gateway-worker/process.php
这里定义了两个协议,tcp 用来对接物联网,ws 用来对接im
<?php
use Webman\GatewayWorker\Gateway;
use Webman\GatewayWorker\BusinessWorker;
use Webman\GatewayWorker\Register;
return [
'gateway' => [
'handler' => Gateway::class,
'listen' => 'websocket://0.0.0.0:7272',
'count' => 2,
'reloadable' => false,
'constructor' => ['config' => [
'lanIp' => '127.0.0.1',
'startPort' => 2300,
'pingInterval' => 25,
'pingData' => '{"type":"ping"}',
'registerAddress' => '127.0.0.1:1236',
'onConnect' => function(){},
]]
],
'gateway-tcp' => [ // 假设增加一个tcp端口的gateway进程
'handler' => Gateway::class,
'listen' => 'tcp://0.0.0.0:8383', // 注意这里端口不能重复
'count' => cpu_count(),
'reloadable' => false,
'constructor' => ['config' => [
'lanIp' => '127.0.0.1',
'startPort' => 3300, // 注意这里端口不能重复,步数大大一些,不能和上面2300太接近
'pingInterval' => 25,
'pingData' => '{"type":"ping"}',
'registerAddress' => '127.0.0.1:1236',
'onConnect' => function(){},
]]
],
'worker' => [
'handler' => BusinessWorker::class,
'count' => cpu_count()*2,
'constructor' => ['config' => [
'eventHandler' => plugin\webman\gateway\Events::class,
'name' => 'ChatBusinessWorker',
'registerAddress' => '127.0.0.1:1236',
]]
],
'register' => [
'handler' => Register::class,
'listen' => 'text://127.0.0.1:1236',
'count' => 1, // Must be 1
'reloadable' => false,
'constructor' => []
],
];
文件:plugin/webman/gateway/Events.php
这里im 和 tcp 公用一套,需要注意要根据bind 的uid 来区别
<?php
namespace plugin\webman\gateway;
use GatewayWorker\Lib\Gateway;
class Events
{
public static function onWorkerStart($worker)
{
}
public static function onConnect($client_id)
{
var_dump(5555,$client_id);
Gateway::bindUid($client_id, '1');
}
public static function onWebSocketConnect($client_id, $data)
{
}
public static function onMessage($client_id, $message)
{
var_dump(666,$client_id,$message);
Gateway::sendToClient($client_id, "receive message $message");
}
public static function onClose($client_id)
{
}
}
文件:controller/IndexController.php
这里是在方法内主动发送数据
<?php
namespace app\controller;
use support\Request;
use GatewayWorker\Lib\Gateway;
class IndexController
{
public function index(Request $request)
{
$uid='1';
//查看是否在线
var_dump('是否在线',!!Gateway::isUidOnline($uid));
if(Gateway::isUidOnline($uid)){
$message = "lizhili--" . date('H:i:s');
Gateway::sendToUid($uid, $message . "\n");
}
return json(['code' => 0, 'msg' => 'ok']);
}
}
有个不错的 tcp 协议的测试工具
可以简单的测试 tcp 的链接发送,也可以做客户端
https://gitcode.com/open-source-toolkit/d6985/?utm_source=tools_gitcode&index=bottom&type=card
下载地址