**
1. 安装workerman/gateway-worker
**
composer require workerman/gateway-worker
2.根目录创建server.php
<?phpnamespace think;
require __DIR__ . '/thinkphp/base.php';
Container::get('app')->bind('worker/server')->run()->send();
3.创建启动文件app\worker\controller\server.php
默认demo 无法使用tp中的类,这里就自己写了
gatewayworker中的所有类方法全部放到这里
<?phpnamespace app\worker\controller;use GatewayWorker\Gateway;
use \Workerman\Worker;
use \GatewayWorker\BusinessWorker;
use \GatewayWorker\Register;class Server
{public function __construct(){if (strpos(strtolower(PHP_OS), 'win') === 0) {exit("start.php not support windows, please use start_for_win.bat\n");}// 检查扩展if (!extension_loaded('pcntl')) {exit("Please install pcntl extension. See http://doc3.workerman.net/appendices/install-extension.html\n");}if (!extension_loaded('posix')) {exit("Please install posix extension. See http://doc3.workerman.net/appendices/install-extension.html\n");}$this->startGateWay();$this->startBusinessWorker();$this->startRegister();Worker::runAll();}public function startGateWay(){// wss服务$context = [];// gateway 进程,这里使用Text协议,可以用telnet测试$gateway = new Gateway('websocket://0.0.0.0:1236', $context);// gateway名称,status方便查看$gateway->name = 'HsxGateWay';// gateway进程数$gateway->count = 4;// 本机ip,分布式部署时使用内网ip$gateway->lanIp = '127.0.0.1';// 内部通讯起始端口,假如$gateway->count=4,起始端口为4000// 则一般会使用4000 4001 4002 4003 4个端口作为内部通讯端口$gateway->startPort = 4000;// 服务注册地址$gateway->registerAddress = '127.0.0.1:1238';// 心跳间隔$gateway->pingInterval = 55;$gateway->pingNotResponseLimit = 1;}public function startBusinessWorker(){// businessWorker 进程$worker = new BusinessWorker();// worker名称$worker->name = 'HsxBusiness';// businessWorker进程数量$worker->count = 4;// 服务注册地址$worker->registerAddress = '127.0.0.1:1238';// 命名空间$worker->eventHandler = 'app\worker\controller\events';}public function startRegister(){// register 必须是text协议$register = new Register('text://0.0.0.0:1238');}
}
4.业务逻辑,只需关注这一个文件即可
<?phpnamespace app\worker\controller;use GatewayWorker\Lib\Gateway;
use think\facade\Env;class Events
{/*** 当客户端连接时触发*/public static function onConnect($clientId){}/*** 当客户端发来消息时触发*/public static function onMessage($clientId, $message){// 这里可以使用tp中的Env了Gateway::sendToClient($clientId, $message . Env::get('APP.API_URL'));}/*** 当用户断开连接时触发*/public static function onClose($clientId){}
}
使用过程中有什么问题欢迎反馈
目前还没发现问题,一切运行正常
创作不易,转载请标明出处