thinkphp6 workerman无法使用框架Db/model相关操作解决
- 执行安装相关扩展
composer require webman/gateway-worker
- 引入成功后编辑服务类文件,直接展示代码
php
<?php
namespace app\server\controller;
use GatewayWorker\BusinessWorker;
use GatewayWorker\Gateway;
use GatewayWorker\Register;
use Workerman\Worker;
class SocketServe
{
public function __construct()
{
$this->start_register();
$this->start_gateway();
$this->start_businessworker();
// 运行所有服务
Worker::runAll();
}
public function start_register()
{
// register 必须是text协议,切记不能将register端口开放给外网
$register = new Register('text://127.0.0.1:1238');
}
public function start_gateway()
{
// gateway 进程,这里使用Text协议,可以用telnet测试
// $gateway = new Gateway("tcp://0.0.0.0:8282");
$gateway = new Gateway("websocket://0.0.0.0:8282");
// gateway名称,status方便查看
$gateway->name = 'YourAppGateway';
// gateway进程数,一般设置2个就足够
$gateway->count = 2;
// 本机ip,分布式部署时使用内网ip
$gateway->lanIp = '127.0.0.1';
// 内部通讯起始端口,假如$gateway->count=2,起始端口为2900
// 则一般会使用2900 2901 2个端口作为内部通讯端口
$gateway->startPort = 2900;
// 服务注册地址
$gateway->registerAddress = '127.0.0.1:1238';
// 心跳间隔
$gateway->pingInterval = 20;
$gateway->pingNotResponseLimit = 0;
// 心跳数据
$gateway->pingData = '接受心跳';
}
public function start_businessworker()
{
$worker = new BusinessWorker();
// worker名称
$worker->name = 'YourAppBusinessWorker';
// bussinessWorker进程数量
$worker->count = 4;
// 服务注册地址
$worker->registerAddress = '127.0.0.1:1238';
//设置处理业务的类,此处制定Events的命名空间
$worker->eventHandler = 'app\server\controller\Even';
}
}
- 业务处理代码(测试使用)
php
<?php
namespace app\server\controller;
use GatewayWorker\Lib\Gateway;
class Even
{
public static function onWebSocketConnect($client_id, $data)
{
var_export($data);
if (!isset($data['get']['token'])) {
Gateway::closeClient($client_id);
}
}
// 当有客户端连接时,将client_id返回,让mvc框架判断当前uid并执行绑定
public static function onConnect($client_id)
{
Gateway::sendToCurrentClient("Your client_id is $client_id");
}
// GatewayWorker建议不做任何业务逻辑,onMessage留空即可
public static function onMessage($client_id, $message){
$name = \think\facade\Db::table('user')->save(['name'=>$message]);
// 群聊,转发请求给其它所有的客户端
return GateWay::sendToAll($message);
}
}
- 在根目录创建启动文件
php
<?php
// [ 应用入口文件 ]
namespace think;
require __DIR__ . '/../vendor/autoload.php';
//加载框架并初始化应用(这样才能直接使用框架自带的一些类库方法)
$http = (new App())->initialize()->make('app\server\controller\SocketServe');
- 启动服务
php serve.php start
启动成功
结束 测试一切正常