Exemplo n.º 1
0
 /**
  * 异步任务
  *
  * @param $serv
  * @param $task_id
  * @param $from_id
  * @param $data
  */
 public function task($serv, $task_id, $from_id, $data)
 {
     static $db = null;
     static $cache = null;
     if (!$db) {
         $db = new DB();
     }
     if (!$cache) {
         $cache = new Cache();
     }
     $d = json_decode($data, true);
     $type = $d['type'];
     unset($d['type']);
     //获取在线用户列表
     $onlines = $db->fetch_all('select * from %t where 1', array('online'));
     $notme = false;
     $message = "";
     switch ($type) {
         //处理消息
         case 'message':
             #1 将用户消息入库
             $db->insert("message", $d);
             $notme = true;
             $message = $d['msg'];
             $type = self::TYPE_NORMAL;
             break;
             //推送在线会员列表
         //推送在线会员列表
         case 'pushOnline':
             $message = $db->fetch_all("select * from %t where 1", array('online'));
             $type = self::TYPE_PUSH_ONLINEMEMBERS;
             //给单独用户推送在线会员列表
             if ($d['sendto']) {
                 $msg = $this->createRecMsg($message, $type);
                 $serv->send((int) $d['sendto'], $this->frame($msg), $from_id);
             }
             break;
         case 'login':
             if ($db->fetch_first("select * from %t where openid=%s", array('online', $d['openid']))) {
                 $db->update('online', array('fd' => $d['fd']), " openid='" . $d['openid'] . "'");
                 $cache->set($d['fd'], $d['openid']);
             } else {
                 $serv->close($d['fd']);
             }
             break;
         case 'logout':
             $cache->delete($d['fd']);
             break;
     }
     //检查登陆授权
     var_dump($cache->get($d['fd']));
     //		if(!$cache->get($d['fd'])) { $serv->close($d['fd']); }
     //将消息发给在线用户
     if ($onlines) {
         echo date("H:i:s") . " : 当前有 " . count($onlines) . " 人在线,开始发送消息 == " . json_encode($message) . " \n";
         foreach ($onlines as $key => $val) {
             if ($notme && $val['fd'] == $d['fd']) {
                 continue;
             }
             $msg = $this->createRecMsg($message, $type, $val['fd']);
             //开始发送消息
             $serv->send((int) $val['fd'], $this->frame($msg), $from_id);
         }
     } else {
         echo "没有在线用户";
     }
 }