TP6 中使用 gateway-worker
安装:
composer require topthink/think-worker
更新镜像
composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/
配置:在config/下面有三个文件,修改端口
gateway_worker.php
worker.php
worker_server.php
//BusinsessWorker配置
'businessWorker' => [
'name' => 'BusinessWorker',
'count' => 1,
'eventHandler' => '\app\http\Events', //业务代码地址
],
启动:php think worker:gateway 关闭终端停止运行
推荐启动:php think worker:gateway -d 关闭终端依然运行
停止:php think worker:gateway stop
## wss 配置
* apache 配置: 开放一个端口,并在宝塔网站设置配置文件中加入以下代码。
SSLProxyEngine on
ProxyRequests Off
ProxyPass /wss ws://127.0.0.1:端口
ProxyPassReverse /wss wss://127.0.0.1:端口
* nginx 配置:开放一个端口,并在宝塔网站设置配置文件加入以下代码。
location /wss {
proxy_pass http://127.0.0.1:端口;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
rewrite /wss/(.*) /$1 break;
proxy_redirect off;
}
## 本地访问wss: ws://www.xxx.com/wss 或者 ws://ip:端口
## 前端访问wss: wss://www.xxx.com/wss
后端业务代码:
initialize(); } public static function onConnect($client_id) { //Gateway::sendToCurrentClient("Your client_id is $client_id"); } public static function onWebSocketConnect($client_id, $data) { //var_export($data); } public static function onMessage($client_id, $data) { $arr = json_decode($data); if($arr->type == "bind"){ //绑定客户端 Gateway::bindUid($client_id, $arr->id); }else{ //一对一聊天 if($arr->mode=="single"){ Gateway::sendToUid($arr->receive_id, $data); } //群聊天 if($arr->mode=="group"){ $group_user_ids = [1,2,3]; //模拟群用户ID集合 foreach($group_user_ids as $key=>$value){ if($value != $arr->id){ Gateway::sendToUid($value, $data); } } } } } public static function onClose($client_id) { GateWay::sendToAll(json_encode(['type'=>'close'])); } public static function onWorkerStop(Worker $businessWorker) { echo "WorkerStop\n"; }}
前端连接:
来源地址:https://blog.csdn.net/u012015434/article/details/127072319