实例化 $io = new SocketIO(2021);后,再绑定事件workerStart方法时,调用to方法,报方法错误
问题出现的环境背景及自己尝试过哪些方法
相关代码
// 请把代码文本粘贴到下方(请勿用图片代替代码)
$io = new SocketIO(2021);
$io->on('connection', function ($socket) use ($io) {
//监听客户端连接成功发送数据,记录在线状态,并发送统计数据
$socket->on('success', function ($msg) use ($io, $socket) {
$companyId = $msg['company_id'];
if ($companyId) {
$socket->username = $companyId;
$int = Db::table('v_socket')->where(['shop_id' => $companyId])->find();
if (empty($int)) {
$add = [
'shop_id' => $companyId,
'socket_status' => 1,
'create_time' => date('Y-m-d H:i:s')
];
Db::table('v_socket')->insert($add, false, true);
} else {
if ($int['socket_status'] == 2) {
Db::table('v_socket')->where(['shop_id' => $companyId])->update(['socket_status' => 1]);
}
}
// $redis = Cache::store('redis')->handler();
// $redis->set("webSocket:company_" . $companyId, 1);
//发送统计数据
$index = new Index();
$res = $index->census($companyId);
$socket->emit('success', json_encode($res, JSON_UNESCAPED_UNICODE));
}
});
//关闭连接,修改该用户的状态
$socket->on('disconnect', function () use ($socket) {
$where = [
'shop_id' => $socket->username,
];
Db::table('v_socket')->where($where)->update(['socket_status' => 2]);
});
});
// 当$io启动后监听一个http端口,通过这个端口可以给任意uid或者所有uid推送数据
$io->on('workerStart', function () {
// 监听一个http端口
$inner_http_worker = new Worker('http://10.18.16.56:2121/');
// 当http客户端发来数据时触发
$inner_http_worker->onMessage = function ($http_connection, $data) {
$_POST = $_POST ? $_POST : $_GET;
// 推送数据的url格式 type=publish&to=uid&content=xxxx
switch (@$_POST['type']) {
case 'publish':
global $io;
$to = @$_POST['to'];
$_POST['content'] = htmlspecialchars(@$_POST['content']);
// 有指定uid则向uid所在socket组发送数据
if ($to) {
$io->to($to)->emit('new_msg', $_POST['content']);
// 否则向所有uid推送数据
} else {
$io->emit('new_msg', @$_POST['content']);
}
}
return $http_connection->send($data);
};
// 执行监听
$inner_http_worker->listen();
});
Worker::runAll();
}