thinkphp6使用workerman
·
<?php
namespace app\http;
use think\worker\Server;
class Worker extends Server
{
protected $socket = 'websocket://0.0.0.0:2346';
// 用户组
protected $uidArr = [];
public function onMessage($connection, $data)
{
$rest = $this->json_done($data);
$type = (int)$rest['type'];
switch ($type) {
case 1: // 握手
if (!isset($connection->uid)) {
$connection->uid = $rest['uid'];
$this->uidArr[$connection->uid] = $connection;
}
break;
case 2: // 内容
$textJson = [
'content' => $rest['content'],
'name' => $rest['name'],
'image' => $rest['image']
];
$this->sendByUid($rest['tid'], json_encode($textJson)); // 指定消息
//$this->sendAllUid(json_encode($textJson)); // 消息广播
break;
default:
return false;
}
}
/**
* 当连接建立时触发的回调函数
* @param $connection
*/
public function onConnect($connection)
{
}
/**
* 当连接断开时触发的回调函数
* @param $connection
*/
public function onClose($connection)
{
}
/**
* 当客户端的连接上发生错误时触发
* @param $connection
* @param $code
* @param $msg
*/
public function onError($connection, $code, $msg)
{
echo "error $code $msg\n";
}
/**
* 每个进程启动
* @param $worker
*/
public function onWorkerStart($worker)
{
}
/**
* 发送消息给指定用户
* @param $uid
* @param $message
*/
public function sendByUid($uid, $message)
{
if (isset($this->uidArr[$uid])) {
$connection = $this->uidArr[$uid];
$connection->send($message);
}
}
/**
* 消息广播
* @param $message
*/
public function sendAllUid($message)
{
foreach ($this->uidArr as $connection) {
$connection->send($message);
}
}
/**
* 解析前端回传的json数据
* @param $data
* @return mixed
*/
public function json_done($data)
{
$rest = json_decode($data, true);
return $rest;
}
}
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)