server.php如下:
<?php
define('APP_PATH', __DIR__ . '/bookapp/');
define('BIND_MODULE','kenny/Gate');
// 加载框架引导文件
require __DIR__ . '/thinkphp/start.php';
Gage.php文件如下:
namespace app\kenny\controller;
use Workerman\Worker;
use GatewayWorker\Gateway;
use GatewayWorker\Register;
use GatewayWorker\BusinessWorker;
class Gate{
/**
* 构造函数
* @access public
*/
public function __construct(){
//初始化各个GatewayWorker
//初始化register register 服务必须是text协议
$register = new Register('text://0.0.0.0:1237');
//初始化 bussinessWorker 进程
$worker = new BusinessWorker();
// worker名称
$worker->name = 'AppBusinessWorker';
// bussinessWorker进程数量
$worker->count = 2;
// 服务注册地址
$worker->registerAddress = '192.168.18.9:1237';
//设置处理业务的类,此处制定Events的命名空间
$worker->eventHandler = 'app\kenny\controller\Events';
// 初始化 gateway 进程
$gateway = new Gateway("book://0.0.0.0:9526");
// 设置名称,方便status时查看
$gateway->name = 'AppGateway';
$gateway->count = 1;
// 分布式部署时请设置成内网ip(非127.0.0.1)
$gateway->lanIp = '192.168.18.9';
$gateway->startPort = 2300;
// 心跳间隔
$gateway->pingInterval = 180;
$gateway->pingNotResponseLimit = 1;
// 心跳数据
$gateway->pingData = "ping";
// 服务注册地址
$gateway->registerAddress = "192.168.18.9:1237";
//运行所有Worker;
Worker::runAll();
}
}
Events.php如下:
<?php
namespace app\kenny\controller;
use \GatewayWorker\Lib\Gateway;
class Events{
public static function onConnect($client_id){
Gateway::sendToCurrentClient('onConnect:'.$client_id);
}
public static function onMessage($client_id,$message){
//判断是否绑定了uid
if (!isset($client_id->uid)){
echo "no uid\n";
Gateway::bindUid($client_id,2);
}else{
echo "uid\n";
}
}
}
//收到消息时,始终输出 no uid ,请问如何在onMessage里识别当前是否绑定了uid ?
Gateway :: getUidByClientId($ client_id)返回client_id绑定的uid,如果client_id没有绑定uid,则返回null。
Gateway::getUidByClientId(string $client_id)
基本接口使用看手册就好
$ret = Gateway::getUidByClientId($client_id);
if (!$ret){
}else{
echo "uid\n";
}修改成这样了,连接上后,每次收到消息,都判断为no uid 这是哪里没有用对?
你是不是没有调用 Gateway::bindUid()绑定UID
绑定了,见上文:Gateway::bindUid($client_id,2);
那可能是局部的逻辑有问题
问题找到了,在使用Gateway::bindUid($client_id,2);时,第二个参数,不能使用数字,改为:
Gateway::bindUid($client_id,'2');就正常了,修改后如下:
$ret = Gateway::getUidByClientId($client_id);
if (!$ret){
}else{
echo "uid\n";
}