Thinkphp8项目集成GatewayClient实现websocket长连接
·
在php开发中,实现websocket服务,一般采用基于workerman的GatewayWorker来开发。官方推荐的整合方案如下图:

总体原则:
- 现有mvc框架项目与GatewayWorker独立部署互不干扰
- 所有的业务逻辑都由网站页面post/get到mvc框架中完成
- GatewayWorker不接受客户端发来的数据,即GatewayWorker不处理任何业务逻辑,GatewayWorker仅仅当做一个单向的推送通道
- 仅当mvc框架需要向浏览器主动推送数据时才在mvc框架中调用Gateway的API GatewayClient完成推送。
一、部署GatewayWorker服务
基于上述原则,将GatewayWorker独立部署到A服务器,官方提供了demo下载,属于即拿即用:
访问https://www.workerman.net/doc/gateway-worker/README.html,下载demo后解压,进入到GatewayWorker目录,执行命令:
cd GatewayWorker
#守护进程方式启动GatewayWorker
php start.php start -d

- 注意 使用websocket协议,需要将start_gateway.php中tcp改成websocket *
二、集成GatewayClient到tp8项目
进入到thinkphp8项目根目录,运行:
composer require workerman/gatewayclient
GatewayClient 3.0.0版本以后加了命名空间,所以在需要使用GatewayWorker服务的控制器引入即可:
use GatewayClient\Gateway;
<?php
namespace app\controller;
use GatewayClient\Gateway;
class Index extends BaseController
{
public function index($uid)
{
Gateway::$registerAddress = '127.0.0.1:1236';
Gateway::sendToUid($uid, json_encode($command));
}
}
GatewayClient支持GatewayWorker中的所有接口(Gateway::closeCurrentClient Gateway::sendToCurrentClient除外)
Gateway::sendToAll($data);
Gateway::sendToClient($client_id, $data);
Gateway::closeClient($client_id);
Gateway::isOnline($client_id);
Gateway::bindUid($client_id, $uid);
Gateway::isUidOnline($uid);
Gateway::isUidsOnline($uids);
Gateway::getClientIdByUid($uid);
Gateway::unbindUid($client_id, $uid);
Gateway::sendToUid($uid, $dat);
Gateway::joinGroup($client_id, $group);
Gateway::sendToGroup($group, $data);
Gateway::leaveGroup($client_id, $group);
Gateway::getClientCountByGroup($group);
Gateway::getClientSessionsByGroup($group);
Gateway::getAllClientCount();
Gateway::getAllClientSessions();
Gateway::setSession($client_id, $session);
Gateway::updateSession($client_id, $session);
Gateway::getSession($client_id);
参考:
https://www.workerman.net/doc/gateway-worker/work-with-other-frameworks.html
https://github.com/walkor/GatewayClient
更多推荐
所有评论(0)