argument('op'); $op = $op? $op : 'start'; if($op == 'start'){ echo 'socket start ...'; $this->start(); }else if ($op == 'stop'){ echo 'socket stop ...'; $this->stop(); } } /** * 运行 */ public function start() { //创建websocket服务器对象,监听0.0.0.0:7104端口 $this->ws = new \swoole_websocket_server("0.0.0.0", env('SOCKET_PORT','6420')); // $this->ws->set(); //监听WebSocket连接打开事件 $this->ws->on('open',[$this,'open']); //监听WebSocket消息事件 $this->ws->on('message',[$this,'message']); //监听WebSocket主动推送消息事件 $this->ws->on('request',[$this,'request']); //监听WebSocket连接关闭事件 $this->ws->on('close',[$this,'close']); $this->ws->start(); } /** * 建立连接 * @param $ws * @param $request */ public function open($ws, $request){ echo "连接成功:".$request->fd."\n"; $this->ws->push($request->fd,'连接成功'); } /** * 接收消息 * @param $ws * @param $frame */ public function message($ws,$frame){ if($frame->data == 'ping'){ $this->ws->push($frame->fd, 'pong'); return false; } // 消息处理 $data = $frame->data? json_decode($frame->data, true) : []; $op = isset($data['op'])? $data['op'] : ''; if($data){ switch($op){ case 'bind': // 绑定用户 if(!ChatMessageService::make()->bind($frame->fd, $data)){ $this->ws->push($frame->fd, lang(ChatMessageService::make()->getError())); return false; } break; default: // 默认聊天 $toUid = isset($data['to_uid'])? intval($data['to_uid']) : 0; $fromUid = isset($data['from_uid'])? intval($data['from_uid']) : 0; $messageType = isset($data['message_type'])? $data['message_type'] : 1; if($toUid<=0 || $fromUid<=0){ return false; } if(!ChatMessageService::make()->saveData($data)){ $this->ws->push($frame->fd, lang(ChatMessageService::make()->getError())); return false; } $toBindData = RedisService::get("chats:bind:{$toUid}"); $toFd = isset($toBindData['fd'])? $toBindData['fd'] : 0; if($toBindData && $toFd){ $toInfo = MemberService::make()->getInfo($toUid); $fromInfo = MemberService::make()->getInfo($fromUid); $message = isset($data['message'])? $data['message'] : ''; $data = [ 'type'=> isset($data['type'])? $data['type'] : 1, 'message_type'=> $messageType, 'from_uid'=> $fromUid, 'from_userName'=> isset($fromInfo['username'])? $fromInfo['username'] : '', 'to_uid'=> isset($data['to_uid'])? $data['to_uid'] : 0, 'to_userName'=> isset($toInfo['username'])? $toInfo['username'] : '', 'chat_key'=> getChatKey($fromUid, $toUid), 'message'=> $messageType==2&&$message? get_image_url($message) : $message, 'create_time'=> time(), 'time_text'=> date('m-d H:i'), 'is_read'=> 1, 'status'=> 1, ]; $this->ws->push($toFd, json_encode($data, 256)); } break; } }else{ $this->ws->push($frame->fd, 'not data'); } } /** * 接收请求 * @param $request * @param $response */ public function request($request,$response){ } /** * 关闭连接 * @param $ws * @param $fd */ public function close($ws,$fd=''){ // var_dump($ws); echo '连接关闭:'.$fd."\n"; $this->ws->close($fd); } /** * 停止运行 */ public function stop($ws) { $this->ws->close(); } }