timerId = GET_TIMER()->add(3000, [$this, 'checkLogin']); } /** * 连接断开前的回调 */ public function onClose() { if ($this->logined) { unset($GLOBALS['users'][$this->id]); //广播离线通知给其他客户端 $msg = new Message(); $msg->set('cmd', 'leave'); $msg->set('id', $this->id); $msg->set('name', $this->name); BC($msg); } } /** * 检查登录状态 */ public function checkLogin() { if (!$this->logined) { $msg = new Message(); $msg->set('cmd', 'logout'); $msg->set('data', 'byebye!'); $this->response($msg, [$this, 'close']); } } /** * 实现的分发请求消息的接口 */ public function onRequest($msg) { $cmd = $msg->get('cmd'); if (empty($cmd)) { return; } switch ($cmd) { case 'time': //请求服务器时间 $this->onTime(); break; case 'test': $this->onTest(); break; case 'dl': //下载图片 $this->onDownload(); break; case 'login': //登录 $this->onLogin($msg); break; case 'bc': //广播 $this->onBC($msg); break; case 'talk': //私聊 $this->onTalk($msg); break; } } /** * 返回服务器时间 */ protected function onTime() { $msg = new Message(); $msg->set('cmd', 'time'); $msg->set('data', time()); $this->response($msg); } /** * 测试接口 */ protected function onTest() { $msg = new Message(); $msg->set('cmd', 'time'); $msg->set('data', 'Hello!'); $this->response($msg); } protected $cache = ''; /** * 测试接口 */ protected function onDownload() { if (empty($this->cache)) { $this->cache = base64_encode(file_get_contents(__DIR__ . '/test.jpg')); } $msg = new Message(); $msg->set('cmd', 'download'); $msg->set('data', $this->cache); $this->response($msg); } /** * 当前客户的名称 * @var string */ protected $name; /** * 返回当前客户的名称 * @return string 客户的名称 */ public function getName() { return $this->name; } /** * 客户端登录处理 * @param Message $msg 请求消息 */ protected function onLogin($msg) { $name = $msg->get('name'); if (empty($name)) { return; } $this->name = $name; $this->logined = true; if ($this->timerId) { GET_TIMER()->clear($this->timerId); $this->timerId = 0; } $GLOBALS['users'][$this->id] = $this; //---- login ---- $data = []; foreach ($GLOBALS['users'] as $id => $cli) { $data[$id] = $cli->getName(); } $msg = new Message(); $msg->set('cmd', 'login'); $msg->set('id', $this->id); $msg->set('data', $data); $this->response($msg); //---- enter ---- $bcMsg = new Message(); $bcMsg->set('cmd', 'enter'); $bcMsg->set('id', $this->id); $bcMsg->set('name', $name); BC($bcMsg); } /** * 客户端广播处理 * @param Message $msg 请求消息 */ protected function onBC($msg) { $msg->set('id', $this->id); $msg->set('name', $this->name); BC($msg); } /** * 客户端私聊处理 * @param Message $msg 请求消息 */ protected function onTalk($msg) { $to = $msg->get('to'); if (isset($GLOBALS['users'][$to])) { $msg->set('id', $this->id); $msg->set('name', $this->name); $msg->set('to_name', $GLOBALS['users'][$to]->getName()); $this->response($msg); $GLOBALS['users'][$to]->response($msg); } } }