ci = &get_instance(); } /** * 处理消息 * @param $server * @param $fd * @param $data * @return MyResponse */ public function handleMessage($server, $fd, $data) { try { $content = json_decode($data, true); $type = $content['type']; $requestId = $content['requestId'] ?: ''; //请求唯一id $targetPlatform = $content['targetPlatform'] ?: ''; //推送平台 $targetUid = $content['targetUid'] ?: ''; //推送用户id 0000表示所有用户 $data = $content['data'] ?: ''; // 推送具体内容 switch ($type) { case self::MST_TYPE_HEARTBEAT: break; case self::MES_TYPE_NOTICE://通知消息 if (!Ws_conn_model::REC_PLAT_FORM[$targetPlatform]) { throw new Exception("不支持的推送平台"); } if ($targetUid) { //发送给指定用户 $userRow = $this->ci->getConnectionByUserId($targetPlatform, $targetUid); if (!$userRow) { throw new Exception("用户不在线"); } echo "发送给用户:" . $userRow->fd . "\n"; // 添加连接有效性检查 $connectionInfo = $server->connection_info($userRow->fd); if ($connectionInfo) { $server->push($userRow->fd, WsResponse::success($type, '新消息', $data)); } else { // 清理无效连接 $this->ci->removeConnection($userRow->fd); echo "用户 " . $userRow->fd . " 连接已失效,已清理记录\n"; throw new Exception("用户不在线"); } } elseif ($targetUid == Ws_conn_model::SEND_ALL) { //发送给所有用户 throw new Exception("暂时不支持发送给所有用户"); } else { throw new Exception("请指定推送用户"); } break; default: throw new Exception("未知的消息类型"); } $server->push($fd, WsResponse::success($type, '处理成功', $content)); return new MyResponse(WsResponse::CODE_SUCCESS, '处理消息成功'); } catch (Exception $e) { return new MyResponse($e->getCode() ?: WsResponse::CODE_ERROR, $e->getMessage()); } } }