Example #1
0
 /**
  * 有消息时
  * @param int $client_id
  * @param string $message
  */
 public static function onMessage($client_id, $message)
 {
     // 获取客户端请求
     $message_data = json_decode($message, true);
     if (!$message_data) {
         return;
     }
     switch ($message_data['type']) {
         case 'login':
             Gateway::sendToCurrentClient('{"type":"welcome","id":' . $client_id . '}');
             break;
             // 更新用户
         // 更新用户
         case 'update':
             // 转播给所有用户
             Gateway::sendToAll(json_encode(array('type' => 'update', 'id' => $client_id, 'angle' => $message_data["angle"] + 0, 'momentum' => $message_data["momentum"] + 0, 'x' => $message_data["x"] + 0, 'y' => $message_data["y"] + 0, 'life' => 1, 'name' => isset($message_data['name']) ? $message_data['name'] : 'Guest.' . $client_id, 'authorized' => false)));
             return;
             // 聊天
         // 聊天
         case 'message':
             // 向大家说
             $new_message = array('type' => 'message', 'id' => $client_id, 'message' => $message_data['message']);
             return Gateway::sendToAll(json_encode($new_message));
     }
 }
Example #2
0
 public static function reply($client_id, $uid)
 {
     if (array_key_exists("to", $uid) && array_key_exists("msg", $uid) && array_key_exists("udid", $uid) && array_key_exists("synckey", $uid)) {
         $udid = $uid["udid"];
         $msg = $uid["msg"];
         $uuid = $uid["to"];
         $synckey = $uid["synckey"];
         $db = Db::instance('user');
         //测试数据库操作
         $devlist = $db->query("select `client_id` from `device_login` where  `synckey`=\"{$synckey}\"");
         if (isset($devlist[0])) {
             foreach ($devlist as $dev) {
                 $dest_cli_id = $dev["client_id"];
                 Gateway::sendToClient($dest_cli_id, array('from' => $udid, 'msg' => preg_replace("#\\\\u([0-9a-f]{4})#ie", "iconv('UCS-2BE', 'UTF-8', pack('H4', '\\1'))", $msg)));
                 //$db->query ("DELETE FROM `device_login` WHERE `client_id` = $dest_cli_id");
             }
             //执行成功
             return array("code" => 0, "msg" => "ok");
         } else {
             //回复超时
             return array("code" => 20003, "msg" => "timeout");
         }
     }
     //参数不完整
     return array('code' => 10007, 'msg' => "error");
 }
Example #3
0
 /**
  * 有消息时
  * @param int $client_id 客户端id
  * @param string $message 请求数据
  */
 public static function onMessage($client_id, $message)
 {
     // to do
     $app = app();
     $app['client_id'] = $client_id;
     print_r("Client request + " . $message . " + \n");
     try {
         $app['request'] = $app['decoder']->decode($message);
     } catch (Webmozart\Json\DecodingFailedException $e) {
         $response['code'] = 400;
         $response['message'] = 'Bad request';
         print_r("Client bad request + " . $app['encoder']->encode($response) . " + \n");
         Gateway::sendToAll($app['encoder']->encode($response));
         return;
     }
     switch ($app['request']->type) {
         case 'pong':
             return;
             break;
         case 'login':
             // $app['bus']->dispatch(new LoginCommand($app));
             break;
         case 'say':
             // $app['bus']->dispatch(new SayCommand($app));
             break;
         default:
             break;
     }
 }
Example #4
0
 /**
  * 当客户端发来消息时触发
  * @param int $client_id 连接id
  * @param string $message 具体消息
  * @link http://gatewayworker-doc.workerman.net/gateway-worker-development/onmessage.html
  */
 public static function onMessage($client_id, $message)
 {
     // 向所有人发送 @see http://gatewayworker-doc.workerman.net/gateway-worker-development/send-to-all.html
     // Gateway::sendToAll("$client_id said $message");
     CustomLogger::getLogger()->info("{$client_id} [RECV] {$message}");
     $data = ProtocolParser::parseProtocolData($message);
     if (is_null($data)) {
         return;
     }
     Gateway::bindUid($client_id, $data->getDeviceSn());
     $cmdParser = CmdFactory::createCMDParserFromProtocolData($data);
     $cmdParser->handleCmd();
 }
Example #5
0
 public static function doApi($client_id, $message)
 {
     // 获取客户端请求
     $data = json_decode($message, true);
     if (!$data) {
         return;
     }
     $re = array();
     $re['type'] = $data['type'];
     $st = 0;
     if ($data['type'] == 'login') {
         Login::doApi($data, $re);
         isset($re['uid']) && Gateway::bindUid($client_id, $re['uid']);
     } else {
         $uid = $data['uid'];
         $player = PlayerDao::getPlayer($uid);
         //            RedisUtil::lock($uid);
         if (!$data['uid'] || !$player) {
             $re['s'] = Constants::RESPONSE_NO_PLAYER;
             Gateway::sendToClient($client_id, json_encode($re));
             //                RedisUtil::unlock($uid);
             return;
         }
         $re['s'] = Constants::RESPONSE_SUCCESS;
         switch ($data['type']) {
             case 'test':
                 $st = Progress::doApi($player, $data, $re, $client_id);
                 break;
             case 'jt':
                 JoinTable::doApi($player, $data, $re);
                 break;
             case 'll':
                 Landlord::doApi($player, $data, $re);
                 break;
             case 'play':
                 $st = Play::doApi($player, $data, $re);
                 break;
             case 'chgSt':
                 ChgPlaySt::doApi($player, $data, $re);
                 break;
             default:
                 $re['s'] = Constants::RESPONSE_FAIL;
                 break;
         }
     }
     if ($st != 1) {
         Gateway::sendToClient($client_id, json_encode($re));
     }
     //        RedisUtil::unlock($uid);
 }
Example #6
0
 public static function onMessage($client_id, $message)
 {
     // 获取客户端请求
     $message_data = json_decode($message, true);
     echo 'message' . $message . 'ID' . $client_id;
     if (!$message_data) {
         return;
     }
     //text-info 是系统发送的。text-user 是其他用户发送的。
     switch ($message_data['type']) {
         case 'JOIN':
             // 转播给所有用户
             Gateway::sendToAll(json_encode(array('type' => 'NOTE', 'id' => $client_id, 'text_type' => 'text-info', 'msg' => $message_data['user_nickname'] . '加入聊天。当前共有' . count(Gateway::getOnlineStatus()) . '把剪子在线。')));
             break;
         case 'QUIT':
             // 转播给所有用户
             GateWay::sendToAll(json_encode(array('type' => 'QUIT', 'msg' => $message_data['from'] . '退出聊天啦 T^T'), true));
             break;
         case 'EDIT':
             // 转播给所有用户
             Gateway::sendToAll(json_encode(array('type' => 'EDIT', 'from' => $message_data['from'], 'to' => $message_data['to'], 'head' => $message_data['head'])));
             break;
         case 'NAME':
             // var_export(Gateway::getOnlineStatus());
             // echo 'online num :'.count(Gateway::getOnlineStatus());
             $id = mt_rand(1, 9);
             Gateway::sendToCurrentClient('{"type":"NAME","head":"http://img3.178.com/acg1/201507/230072993522/230073874484.jpg","name":"剪纸' . $client_id . '号","msg":"大家好,剪纸' . $client_id . '号来啦。"}');
             echo 'NAME IS come ';
             break;
             // 更新用户
         // 更新用户
         case 'POST':
             // 转播给所有用户
             echo 'POST IS IN';
             Gateway::sendToAll(json_encode(array('type' => 'POST', 'from' => $message_data['from'], 'msg' => $message_data['context'], 'head' => $message_data['head'])));
             return;
             // 聊天
         // 聊天
         case 'message':
             // 向大家说
             $new_message = array('type' => 'message', 'id' => $client_id, 'message' => $message_data['message']);
             return Gateway::sendToAll(json_encode($new_message));
     }
 }
Example #7
0
 /**
  * 牌局玩家进度广播
  */
 public static function doApi($player, $data, &$re, $client_id)
 {
     $uid = $player->uid;
     $table = TableDao::getTable($player->tableId);
     if (!$table) {
         return 1;
     }
     if (!Timer::isExistTimer($table->blinkTimeOut)) {
         Gateway::bindUid($client_id, $uid);
         $table->blinkTimeOut = Timer::add(Constants::TABLE_INIT_CHECK_TIME, array($table, 'checkTime'));
         TableDao::addTable($table->tableId, $table);
     }
     if (!isset($table->playerStatus[$uid])) {
         $table->addUid($uid);
         GameDao::addInGamePlayer($uid);
         TableDao::addTable($table->tableId, $table);
     }
     if ($data['st'] == 1) {
         if (!in_array($uid, $table->readyUids)) {
             $table->readyUids[] = $uid;
             TableDao::addTable($table->tableId, $table);
         }
         if (count($table->readyUids) >= 3) {
             $table->recordTime = time();
             TableDao::addTable($table->tableId, $table);
             $re['uid'] = -1;
             Gateway::sendToUid($table->uids, json_encode($re));
         }
     }
     if ($data['addVal'] != -1) {
         $uids = $table->uids;
         $re['uid'] = $uid;
         foreach ($uids as $_uid) {
             if ($_uid == $uid) {
                 continue;
             }
             $re['addVal'] = $data['addVal'];
             $re['oldVal'] = $data['oldVal'];
             Gateway::sendToUid($_uid, json_encode($re));
         }
     }
     return 1;
 }
Example #8
0
 /**
  * 玩家账号注册,确定牌局
  * @param $data
  * @param $re
  * @return int
  */
 public static function doApi($data, &$re)
 {
     if (!isset($data['uid'])) {
         $re['s'] = Constants::RESPONSE_FAIL;
         return 0;
     }
     $uid = $data['uid'];
     $re['uid'] = $uid;
     $player = PlayerDao::getPlayer($uid);
     if (!$player) {
         $ip = $_SERVER['REMOTE_ADDR'];
         $player = new Player($data, $ip);
         PlayerDao::addPlayer($player->uid, $player);
     } else {
         $player->lastLoginIp = $player->loginIp;
         $player->loginIp = $_SERVER['REMOTE_ADDR'];
         $player->loginTime = time();
         $player->tableId = $data['tid'];
         PlayerDao::addPlayer($player->uid, $player);
     }
     $table = TableDao::getTable($player->tableId);
     $nowTime = time();
     if ($table && isset($table->playerStatus[$uid]) && $nowTime - $table->recordTime <= 60 && $table->tableStatus != Constants::TABLE_INIT && $table->tableStatus != Constants::TABLE_END && $table->playerStatus[$uid] != Constants::PLAYER_LEAVE) {
         GameDao::addInGamePlayer($uid);
         $re['s'] = Constants::RESPONSE_RECONN_SUCCESS;
         $tableInfo = $table->getTableInfo($player);
         if ($tableInfo) {
             $re['tableInfo'] = $tableInfo;
             Gateway::sendToUid($uid, json_encode($re));
             return 1;
         }
     }
     if (!$table || $nowTime - $table->initTime >= 120) {
         $table = new Table($data['tid'], $data['uids']);
         TableDao::addTable($table->tableId, $table);
     }
     if ($table && in_array($uid, $table->uids)) {
         $re['s'] = Constants::RESPONSE_SUCCESS;
     } else {
         $re['s'] = Constants::RESPONSE_FAIL;
     }
 }
Example #9
0
 /**
  * 有消息时
  * @param int $client_id
  * @param string $message
  */
 public static function onMessage($client_id, $message)
 {
     // debug
     echo "client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']} gateway:{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']}  client_id:{$client_id} session:" . json_encode($_SESSION) . " onMessage:" . $message . "\n";
     // 客户端传递的是json数据
     $message_data = json_decode($message, true);
     if (!$message_data) {
         return;
     }
     // 根据类型做相应的业务逻辑
     switch ($message_data['type']) {
         // 发送数据给用户 message: {type:send, to_client_id:xx, content:xx}
         case 'send':
             // 向某个浏览器窗口发送消息
             if ($message_data['to_client_id'] != 'all') {
                 $new_message = array('type' => 'send', 'from_client_id' => $client_id, 'to_client_id' => $message_data['to_client_id'], 'content' => nl2br($message_data['content']), 'time' => date('Y-m-d :i:s'));
                 return Gateway::sendToClient($message_data['to_client_id'], json_encode($new_message));
             }
             // 向所有浏览器发送消息
             $new_message = array('type' => 'send', 'from_client_id' => $client_id, 'to_client_id' => 'all', 'content' => nl2br($message_data['content']), 'time' => date('Y-m-d :i:s'));
             return Gateway::sendToAll(json_encode($new_message));
     }
 }
Example #10
0
 public static function doApi($player, $data, &$re)
 {
     $uid = $player->uid;
     if ($player->tableId > 0) {
         $table = TableDao::getTable($player->tableId);
         if ($table && $table->tableStatus == Constants::TABLE_IN_GAME) {
             $op = $data['op'];
             if ($op == 1) {
                 $table->playerStatus[$uid] = Constants::PLAYER_DEPOSIT;
                 $table->noPlayNums[$uid] = 0;
             } else {
                 $table->playerStatus[$uid] = Constants::PLAYER_UN_DEPOSIT;
             }
             TableDao::addTable($table->tableId, $table);
             $re['s'] = Constants::RESPONSE_SUCCESS;
             $re['st'] = $table->playerStatus[$uid];
             $re['uid'] = $uid;
             Gateway::sendToUid($table->uids, json_encode($re));
             return 1;
         }
     }
     $re['s'] = Constants::RESPONSE_FAIL;
     return 0;
 }
Example #11
0
 private function login($client_id, $message_data)
 {
     // 判断是否有房间号
     if (!isset($message_data['room_id'])) {
         throw new \Exception("\$message_data['room_id'] not set. client_ip:{$_SERVER['REMOTE_ADDR']} \$message:{$message}");
     }
     //获取用户客户端登陆的身份
     $uid = $message_data['uid'];
     $room_id = $message_data['room_id'];
     //获取用户提交上来的 房间号
     $_SESSION['room_id'] = $room_id;
     //将房间号存入 session
     $memcache = new Memcache();
     //从缓存服务器中取出当前登陆用户的信息
     $userInfo = $memcache->getUserInfo($uid);
     //从缓存服务器
     $_SESSION['userInfo'] = $userInfo;
     //把缓存数据 存进session 绑定当前连接用户
     $_SESSION['client_name'] = $userInfo['nick_name'] ? $userInfo['nick_name'] : $userInfo['username'];
     // 获取房间内所有用户列表
     $clients_list = Gateway::getClientInfoByGroup($room_id);
     foreach ($clients_list as $tmp_client_id => $item) {
         $clients_list[$tmp_client_id] = ['uid' => $item['userInfo']['id'], 'client_name' => $item['userInfo']['nick_name'] ? $item['userInfo']['nick_name'] : $item['userInfo']['username'], 'head_portrait' => $item['userInfo']['head_portrait']];
     }
     $clients_list[$client_id] = ['uid' => $userInfo['id'], 'client_name' => $userInfo['nick_name'] ? $userInfo['nick_name'] : $userInfo['username'], 'head_portrait' => $userInfo['head_portrait']];
     $id = Gateway::getClientIdByUid($uid);
     //获取id 绑定下的 client_id  1对多关系
     if (empty($id)) {
         //新用户登陆
         // 转播给当前房间的所有客户端,xx进入聊天室 message {type:login, client_id:xx, name:xx}
         $new_message = array('type' => $message_data['type'], 'client_id' => $client_id, 'uid' => $uid, 'head_portrait' => $userInfo['head_portrait'], 'client_name' => $_SESSION['client_name'], 'time' => date('Y-m-d H:i:s'));
         Gateway::sendToGroup($room_id, json_encode($new_message));
         // 发送所有人
         Gateway::joinGroup($client_id, $room_id);
         //将当前连接人 添加到房间内
         Gateway::bindUid($client_id, $uid);
         //将当前连接人 绑定用户id 1对多关系
     } else {
         //页面多开
         Gateway::bindUid($client_id, $uid);
         //将当前连接人 绑定用户id 1对多关系
     }
     // 给当前用户发送用户列表
     $new_message['client_list'] = $clients_list;
     Gateway::sendToCurrentClient(json_encode($new_message));
     return;
 }
Example #12
0
 /**
  * 当客户端断开连接时
  * @param integer $client_id 客户端id
  */
 public static function onClose($client_id)
 {
     // debug
     echo "client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']} gateway:{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']}  client_id:{$client_id} onClose:''\n";
     // 从房间的客户端列表中删除
     if (isset($_SESSION['room_id'])) {
         $room_id = $_SESSION['room_id'];
         $new_message = array('type' => 'game', 'fun' => 'rm_opp()');
         Gateway::sendToGroup($room_id, json_encode($new_message));
     }
 }
Example #13
0
 /**
  * 向客户端推送消息
  * @param array $data 需要推送的消息列表
  * @param array|string $users 需要推送到的用户UID列表
  * @param bool $remove_current_user 是否包含当前用户
  * @throws Exception
  */
 protected static function pushMessageData($data, $users, $remove_current_user = true)
 {
     $client_ids = Message::getClientByUser($users, $remove_current_user);
     $message = json_encode(array('type' => 'push_message', 'result' => array('length' => count($data), 'list' => $data), 'status' => 0, 'msg' => ''));
     Gateway::sendToAll($message, $client_ids);
 }
Example #14
0
 public static function manageDevice($client_id, $uid)
 {
     //var_dump($uid);
     if (array_key_exists("udid", $uid) && array_key_exists("msg", $uid) && array_key_exists("uuid", $uid) && array_key_exists("tdid", $uid) && array_key_exists("synckey", $uid)) {
         $udid = $uid["udid"];
         $uuid = $uid["uuid"];
         $tdid = $uid["tdid"];
         $msg = $uid["msg"];
         $synckey = $uid["synckey"];
         $db = Db::instance('user');
         //测试数据库操作
         //$user = $db->query("select user from user where uuid='$uuid'");
         //if(!isset($user[0]))
         //{ //uuid无效
         //return array("code"=>11004, "msg"=>"username error");
         //}
         $db->query("INSERT INTO `device_login`(`client_id`, `uuid`, `synckey`) VALUES ({$client_id},\"{$uuid}\",\"{$synckey}\")");
         $devlist = $db->query("select `client_id` from `device_login` where `udid`=\"{$udid}\"");
         if (!isset($devlist[0])) {
             //主机没有登录
             return array("code" => 20001, "msg" => "device no login");
         } else {
             $cli_id = $devlist[0]["client_id"];
             if (Gateway::isOnline($cli_id)) {
                 Gateway::sendToClient($cli_id, array('method' => "manage", 'params' => array('tdid' => $tdid, 'src' => "server", 'from' => $uuid, 'synckey' => $synckey, 'msg' => $msg)));
             } else {
                 //主机离线
                 Gateway::closeClient($cli_id);
                 return array("code" => 20002, "msg" => "device offline");
             }
         }
         //发送成功
         return array("code" => 0, "msg" => "ok");
     } else {
         //命令参数不完整
         return array("code" => 10007, "msg" => "params error");
     }
 }
Example #15
0
 /**
  * 当客户端发来消息时触发
  * @param int $client_id 连接id
  * @param string $message 具体消息
  * @link http://gatewayworker-doc.workerman.net/gateway-worker-development/onmessage.html
  */
 public static function onMessage($client_id, $message)
 {
     // 向所有人发送 @see http://gatewayworker-doc.workerman.net/gateway-worker-development/send-to-all.html
     Gateway::sendToAll("{$client_id} said {$message}");
 }
Example #16
0
 /**
  * 有消息时
  * @param int $client_id
  * @param string $message
  */
 public static function onMessage($client_id, $data)
 {
     $class_dir = __DIR__ . "/Services";
     //要读取的类文件路径
     $host_type = "internet";
     //客户端类型
     echo $_SERVER['REMOTE_ADDR'] . "\n";
     if ($_SERVER['REMOTE_ADDR'] == "127.0.0.1") {
         echo "内网登陆";
         $class_dir = __DIR__ . "/SysServices";
         $host_type = "localhost";
         //客户端类型
     }
     echo $_SESSION['UID'] . "\n";
     $statistic_address = 'udp://127.0.0.1:55656';
     // 判断数据是否正确
     if (empty($data['class']) || empty($data['method']) || !isset($data['param_array'])) {
         // 发送数据给客户端,请求包错误
         if ($host_type == "internet" && empty($_SESSION['UID'])) {
             $ret = Gateway::sendToCurrentClient(array('stat' => 100, 'text' => 'no login', 'data' => null));
             Gateway::closeCurrentClient();
         } else {
             $ret = Gateway::sendToCurrentClient(array('stat' => 400, 'text' => 'bad request', 'data' => null));
         }
         return $ret;
     }
     // 获得要调用的类、方法、及参数
     $class = $data['class'];
     $method = $data['method'];
     $param_array = $data['param_array'];
     //所有的调用一定要在登录后才可以
     if (!empty($_SESSION['UID']) || $class == "Device" && $method == "Login" || $host_type == "localhost") {
         StatisticClient::tick($class, $method);
         $success = false;
         // 判断类对应文件是否载入
         if (!class_exists($class)) {
             $include_file = $class_dir . "/{$class}.php";
             if (is_file($include_file)) {
                 require_once $include_file;
             }
             if (!class_exists($class)) {
                 $code = 404;
                 $msg = "class {$class} not found";
                 StatisticClient::report($class, $method, $success, $code, $msg, $statistic_address);
                 // 发送数据给客户端 类不存在
                 //var_dump($connection);
                 return Gateway::sendToCurrentClient(array('stat' => $code, 'text' => $msg, 'data' => null));
             }
         }
         // 调用类的方法
         try {
             $ret = call_user_func_array(array($class, $method), array($client_id, $param_array));
             StatisticClient::report($class, $method, 1, 0, '', $statistic_address);
             // 发送数据给客户端,调用成功,data下标对应的元素即为调用结果
             return Gateway::sendToCurrentClient(array('stat' => 0, 'text' => 'ok', 'data' => $ret));
         } catch (Exception $e) {
             // 发送数据给客户端,发生异常,调用失败
             $code = $e->getCode() ? $e->getCode() : 500;
             StatisticClient::report($class, $method, $success, $code, $e, $statistic_address);
             return Gateway::sendToCurrentClient(array('stat' => $code, 'text' => $e->getMessage(), 'data' => $e));
         }
     } else {
         $ret = Gateway::sendToCurrentClient(array('stat' => 400, 'text' => 'no login', 'data' => null));
         Gateway::closeCurrentClient();
         return $ret;
     }
 }
Example #17
0
 /**
  * 当客户端断开连接时
  * @param integer $client_id 客户端id
  */
 public static function onClose($client_id)
 {
     // debug
     echo "client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']} gateway:{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']}  client_id:{$client_id} onClose:''\n";
     // 从房间的客户端列表中删除
     if (isset($_SESSION['room_id'])) {
         $room_id = $_SESSION['room_id'];
         $new_message = array('type' => 'logout', 'from_client_id' => $client_id, 'from_client_name' => $_SESSION['client_name'], 'time' => date('Y-m-d H:i:s'));
         Gateway::sendToGroup($room_id, json_encode($new_message));
     }
 }
Example #18
0
 /**
  * 当客户端断开连接时
  * @param integer $client_id 客户端id
  */
 public static function onClose($client_id)
 {
     // debug
     // echo "client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']} gateway:{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']}  client_id:$client_id onClose:''\n";
     // 从房间的客户端列表中删除
     $adminUid = 1;
     if (isset($_SESSION['room_id'])) {
         $room_id = $_SESSION['room_id'];
         $uid = $_SESSION['uid'];
         $logined = Gateway::getClientIdByUid($uid);
         //uid 还在线
         if (empty($logined)) {
             $new_message = array('type' => 'logout', 'from_uid_id' => $uid, 'from_client_name' => $_SESSION['client_name'], 'time' => date('Y-m-d H:i:s'));
             Gateway::sendToGroup($room_id, json_encode($new_message));
             //发给管理员,要看所有的在线人数
             $new_logout = ['type' => 'loggoutTwo'];
             Gateway::sendToUid($adminUid, json_encode($new_logout));
         }
     }
 }
Example #19
0
 /**
  * 添加到客户端列表中
  * @param int $client_id
  * @param string $client_name
  */
 public static function addClientToRoom($room_id, $client_id, $client_name)
 {
     $key = "ROOM_CLIENT_LIST-{$room_id}";
     $store = Store::instance('room');
     // 获取所有所有房间的实际在线客户端列表,以便将存储中不在线用户删除
     $all_online_client_id = Gateway::getOnlineStatus();
     // 存储驱动是memcached
     if (get_class($store) == 'Memcached') {
         $cas = 0;
         $try_count = 3;
         while ($try_count--) {
             $client_list = $store->get($key, null, $cas);
             if (false === $client_list) {
                 if ($store->getResultCode() == \Memcached::RES_NOTFOUND) {
                     $client_list = array();
                 } else {
                     throw new \Exception("Memcached->get({$key}) return false and memcache errcode:" . $store->getResultCode() . " errmsg:" . $store->getResultMessage());
                 }
             }
             if (!isset($client_list[$client_id])) {
                 // 将存储中不在线用户删除
                 if ($all_online_client_id && $client_list) {
                     $all_online_client_id = array_flip($all_online_client_id);
                     $client_list = array_intersect_key($client_list, $all_online_client_id);
                 }
                 // 添加在线客户端
                 $client_list[$client_id] = $client_name;
                 // 原子添加
                 if ($store->getResultCode() == \Memcached::RES_NOTFOUND) {
                     $store->add($key, $client_list);
                 } else {
                     $store->cas($cas, $key, $client_list);
                 }
                 if ($store->getResultCode() == \Memcached::RES_SUCCESS) {
                     return $client_list;
                 }
             } else {
                 return $client_list;
             }
         }
         throw new \Exception("addClientToRoom({$room_id}, {$client_id}, {$client_name})->cas({$cas}, {$key}, \$client_list) fail ." . $store->getResultMessage());
     } else {
         $handler = fopen(__FILE__, 'r');
         flock($handler, LOCK_EX);
         $client_list = $store->get($key);
         if (!isset($client_list[$client_id])) {
             // 将存储中不在线用户删除
             if ($all_online_client_id && $client_list) {
                 $all_online_client_id = array_flip($all_online_client_id);
                 $client_list = array_intersect_key($client_list, $all_online_client_id);
             }
             // 添加在线客户端
             $client_list[$client_id] = $client_name;
             $ret = $store->set($key, $client_list);
             flock($handler, LOCK_UN);
             return $client_list;
         }
         flock($handler, LOCK_UN);
     }
     return $client_list;
 }
 /**
  * 当gateway转发来数据时
  * @param TcpConnection $connection
  * @param mixed $data
  */
 public function onGatewayMessage($connection, $data)
 {
     // 上下文数据
     Context::$client_ip = $data['client_ip'];
     Context::$client_port = $data['client_port'];
     Context::$local_ip = $data['local_ip'];
     Context::$local_port = $data['local_port'];
     Context::$connection_id = $data['connection_id'];
     Context::$client_id = Context::addressToClientId($data['local_ip'], $data['local_port'], $data['connection_id']);
     // $_SERVER变量
     $_SERVER = array('REMOTE_ADDR' => long2ip($data['client_ip']), 'REMOTE_PORT' => $data['client_port'], 'GATEWAY_ADDR' => long2ip($data['local_ip']), 'GATEWAY_PORT' => $data['gateway_port'], 'GATEWAY_CLIENT_ID' => Context::$client_id);
     // 尝试解析session
     if ($data['ext_data'] != '') {
         $_SESSION = Context::sessionDecode($data['ext_data']);
     } else {
         $_SESSION = null;
     }
     // 备份一次$data['ext_data'],请求处理完毕后判断session是否和备份相等,不相等就更新session
     $session_str_copy = $data['ext_data'];
     $cmd = $data['cmd'];
     if ($this->processTimeout) {
         pcntl_alarm($this->processTimeout);
     }
     // 尝试执行Event::onConnection、Event::onMessage、Event::onClose
     switch ($cmd) {
         case GatewayProtocol::CMD_ON_CONNECTION:
             if ($this->_eventOnConnect) {
                 call_user_func($this->_eventOnConnect, Context::$client_id);
             }
             break;
         case GatewayProtocol::CMD_ON_MESSAGE:
             if ($this->_eventOnMessage) {
                 call_user_func($this->_eventOnMessage, Context::$client_id, $data['body']);
             }
             break;
         case GatewayProtocol::CMD_ON_CLOSE:
             if ($this->_eventOnClose) {
                 call_user_func($this->_eventOnClose, Context::$client_id);
             }
             break;
     }
     if ($this->processTimeout) {
         pcntl_alarm(0);
     }
     // 判断session是否被更改
     $session_str_now = $_SESSION !== null ? Context::sessionEncode($_SESSION) : '';
     if ($session_str_copy != $session_str_now) {
         \GatewayWorker\Lib\Gateway::updateSocketSession(Context::$client_id, $session_str_now);
     }
     Context::clear();
 }
Example #21
0
 /**
  * 有消息时
  * @param int $client_id
  * @param string $message
  */
 public static function onMessage($client_id, $message)
 {
     $db = Db::instance('db');
     // debug
     //echo "client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']} gateway:{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']}  client_id:$client_id session:".json_encode($_SESSION)." onMessage:".$message."\n";
     //$db->query("INSERT INTO `hs_test` (`ip`, `content`) VALUES ('".$_SERVER['REMOTE_ADDR']."','".$client_id."')");
     $select = $db->query("select `content`,`ip` from `hs_test`");
     //var_dump($select);
     foreach ($select as $v) {
         $clients[$v['ip']][] = $v['content'];
     }
     //var_dump($clients);
     // echo $message;
     ///echo $client_id;
     // 客户端传递的是json数据
     $message_data = json_decode($message, true);
     if (!$message_data) {
         return;
     }
     var_export($message_data);
     // 根据类型做相应的业务逻辑
     switch ($message_data['type']) {
         // 发送数据给用户 message: {type:send, to_client_id:xx, content:xx}
         case 'login':
             //$db = Db::instance('db');
             $db->update('hs_craftsman')->cols(array('client_id' => $client_id))->where('craftsmanid=' . $message_data['id'])->query();
             $db->query("INSERT INTO `hs_test` (`ip`, `content`) VALUES ('" . $message_data['id'] . "','" . $client_id . "')");
             break;
         case 'group':
             echo $message_data['id'] . "\n";
             $db->query("INSERT INTO `hs_test` (`ip`, `content`) VALUES ('" . $message_data['id'] . "','" . $client_id . "')");
             break;
         case 'order':
             if (empty($message_data['data'])) {
                 return;
             }
             /*	$send_data = array();
             			$send_data['type']  = $message_data['data']['order_type'];
             			$send_data['orderid']    = $message_data['data']['orderid'];
             			$client_array_id = self::merge_client_id($clients,$message_data['data']['to_client_id']);
             			echo "***************************";
             			var_export($client_array_id);
             			Gateway::sendToAll(json_encode($send_data),$client_array_id);        		
                   		*/
             foreach ($message_data['data'] as $data) {
                 $send_data = array();
                 echo $send_data['type'] = $data['order_type'];
                 echo "****************\n";
                 $send_data['orderid'] = $data['orderid'];
                 //var_export($data['to_client_id']);
                 //echo ('-----------/n');
                 $client_array_id = self::merge_client_id($clients, $data['to_client_id']);
                 var_export($client_array_id);
                 Gateway::sendToAll(json_encode($send_data), $client_array_id);
             }
             break;
         case 'send':
             //var_dump($message_data['data']);
             if (is_array($message_data['data'])) {
                 //向群组发
                 foreach ($message_data['data'] as $data) {
                     $new_message = array('type' => 'send', 'from_client_id' => $client_id, 'to_client_id' => $data['to_client_id'], 'orderid' => $data['orderid'], 'time' => date('Y-m-d H:i:s'));
                     $client_array_id = self::merge_client_id($clients, $data['to_client_id']);
                     //	var_dump($data['to_client_id']);
                     //echo "**********".$client_id."************";
                     //var_dump($client_array_id);
                     Gateway::sendToAll(json_encode($new_message), $client_array_id);
                     //return Gateway::sendToAll(json_encode($new_message),array(97,98,99));
                     //return Gateway::sendToAll(json_encode($new_message));
                 }
             } else {
                 if ($message_data['to_client_id'] != 'all') {
                     $new_message = array('type' => 'send', 'from_client_id' => $client_id, 'to_client_id' => $message_data['to_client_id'], 'orderid' => nl2br($message_data['orderid']), 'time' => date('Y-m-d H:i:s'));
                     return Gateway::sendToClient($message_data['to_client_id'], json_encode($new_message));
                 } else {
                     // 向所有浏览器发送消息
                     $new_message = array('type' => 'send', 'from_client_id' => $client_id, 'to_client_id' => 'all', 'orderid' => nl2br($message_data['orderid']), 'time' => date('Y-m-d H:i:s'), 'ss' => 'taotao');
                     return Gateway::sendToAll(json_encode($new_message));
                 }
             }
             return true;
             //$db = Db::instance('db');
             //$data = $db->update("SELECT ID,Sex FROM `hs_admin` WHERE userid=1");
             //echo $row_count = $db->update('hs_admin')->cols(array('roleid'=>'10'))->where('userid=1')->query();
             //var_dump($data);
     }
 }
Example #22
0
 /**
  * 当客户端发来消息时触发
  * @param  int
  * @param  string
  * @return void
  */
 public static function onMessage($client_id, $message)
 {
     /**
      * 得到客户端的IP和端口号
      * var_dump($_SERVER['REMOTE_ADDR'].':'.$_SERVER['REMOTE_PORT']);
      */
     //     	// var_export(json_encode($message, JSON_UNESCAPED_UNICODE));
     //     	// $data = json_encode($message, JSON_UNESCAPED_UNICODE);
     //   	// if( $fileType != 'UTF-8'){
     //    //  	$data = mb_convert_encoding($message['macid'] ,'utf-8' , $fileType);
     //    //  	}
     //    //  	var_export($data);
     //     	// var_export($message);
     $connectHC = Db::instance('ConnectHC');
     // 没有登录
     if (!isset($_SESSION['bind'])) {
         // 接收到的是JSON数据包
         if (is_array($message)) {
             self::bindMacId($client_id, $message['macid']);
             return;
         }
         // 回复心跳包
         Gateway::sendToCurrentClient(1);
     } else {
         var_dump($message);
         Gateway::sendToCurrentClient(1);
         if (is_array($message)) {
             // 更新蓝牙连接标志
             if (isset($message['sign'])) {
                 $sign = $message['sign'];
                 $data = $connectHC->query("UPDATE `WEBHC` SET `sign` = {$sign} WHERE clientid={$client_id}");
                 Gateway::sendToCurrentClient(self::SUCCESS_SET_SIGN);
                 return;
             }
             // 更新CLIENTID
             if (isset($message['macid'])) {
                 self::bindMacId($client_id, $message['macid']);
                 return;
             }
             // 更新APP键名
             $param = $connectHC->row("SELECT `param` FROM `WEBHC` WHERE clientid={$client_id}");
             $parambefore = explode('/', $param['param']);
             foreach ($message as $key => $value) {
                 $parambefore[$key - 1] = $value;
             }
             $paramafter = implode('/', $parambefore);
             $connectHC->query("UPDATE `WEBHC` SET `param` = '{$paramafter}' WHERE clientid={$client_id}");
         } else {
             // 回复心跳包
             Gateway::sendToCurrentClient(1);
         }
     }
 }
Example #23
0
 /**
  * 当客户端发来消息时触发
  * @param int $client_id 连接id
  * @param mixed $message 具体消息
  */
 public static function onMessage($client_id, $message)
 {
     // 向所有人发送
     Gateway::sendToAll("{$client_id} said {$message}");
 }
Example #24
0
 /**
  * 不允许多用户登录
  * 剔除存储用户
  */
 public static function notAllowMoreClient($clientList, $clientName)
 {
     if (is_array($clientList)) {
         $unsetKey = array_keys($clientList, $clientName);
         if ($unsetKey) {
             Gateway::sendToAll(json_encode(array('type' => 'error', 'info' => 'loginconflict', 'msg' => '您已在另一客户端登陆')), $unsetKey);
             foreach ($unsetKey as $unkey) {
                 unset($clientList[$unkey]);
                 //下线用户
                 Gateway::closeClient($unkey);
                 //删除存储用户
                 RedisModel::hashDel('webChat', Storekey::USER_ONLINE_LIST, $unkey);
             }
         }
     }
     return;
 }
Example #25
0
 /**
  * 地主确认信息
  * @param $table
  * @param $re
  * @return mixed
  */
 public static function sendInfo($table, $re, $uid = 0)
 {
     $re['s'] = Constants::RESPONSE_SUCCESS;
     $re['st'] = Constants::LANDLORD_ENSURE;
     $re['lUid'] = $table->landlordUid;
     $re['tableSt'] = $table->tableStatus;
     $re['rTime'] = $table->recordTime;
     $re['multiple'] = $table->multiple;
     foreach ($table->uids as $_uid) {
         if ($_uid != $uid) {
             Gateway::sendToUid($_uid, json_encode($re));
         }
     }
     return $re;
 }
Example #26
0
 public static function onMessage($client_id, $message)
 {
     // var_dump(self::get_cpufree());
     Gateway::sendToCurrentClient($message);
 }
Example #27
0
 /**
  * 当客户端发来消息时触发
  * @param  int $client_id
  * @param  string $message
  * @return void
  */
 public static function onMessage($client_id, $message)
 {
     // 得到协议版本
     $wifiversion = substr($message, 4, 2);
     // 得到消息中的目的源地址
     $targetaddr = substr($message, 8, 12);
     // 得到消息中的数据源地址
     $startaddr = substr($message, 20, 12);
     // 得到数据类型
     $messageClass = substr($message, 33, 1);
     // 得到心跳包类型
     $onlinedata = substr($message, 35, 1);
     // var_dump($client_id.'--0--'.bin2hex($message));
     // 判断心跳包
     if ($onlinedata === "�" && isset($_SESSION['registflag'])) {
         // 收到心跳包重新定时
         self::updateTimeid($client_id);
         return;
     }
     // 注册成功返回信息 && 发送失败返回信息
     if (!isset($_SESSION["registsuccess"]) && !isset($_SESSION["transerror"])) {
         $_SESSION["registsuccess"] = "++HC*" . $startaddr . Protocol::$V1['DEFALUT_SMAC'] . Protocol::$V1['SERVER_MODEL'] . "" . Protocol::$V1['STATUS_CONNECTED'] . "�HC\r\n";
         $_SESSION["transerror"] = "++HC*" . $startaddr . Protocol::$V1['DEFALUT_SMAC'] . Protocol::$V1['SERVER_MODEL'] . "" . Protocol::$V1['STATUS_DISONLINE'] . "�HC\r\n";
     }
     // 客户端之间通讯
     if ($wifiversion === "" && $targetaddr !== Protocol::$V1['DEFALUT_SMAC']) {
         // 判断$_SESSION缓存中客户端client_id是否在线
         if (isset($_SESSION["{$targetaddr}"]) && Gateway::isOnline($_SESSION["{$targetaddr}"])) {
             // if($messageClass === "\x02"){
             // 	// 记录控制次数
             // 	self::$connectHC->query("UPDATE `HC` SET `control` = `control`+1 WHERE macid='$startaddr'");
             // }
             // var_dump($_SESSION["$targetaddr"].'--1--'.bin2hex($message));
             Gateway::sendToClient($_SESSION["{$targetaddr}"], $message);
             return;
         }
         // 得到目的客户端client_id
         $targetaddrclientid = self::$connectHC->single("SELECT clientid FROM `HC` WHERE macid='{$targetaddr}'");
         // 如果目的客户端在线则转发
         if (Gateway::isOnline($targetaddrclientid)) {
             // 写入$_SESSION缓存
             $_SESSION["{$targetaddr}"] = intval($targetaddrclientid);
             // if($messageClass === "\x02"){
             // 	// 记录控制次数
             // 	self::$connectHC->query("UPDATE `HC` SET `control` = `control`+1 WHERE macid='$startaddr'");
             // }
             // var_dump($_SESSION["$targetaddr"].'--'.bin2hex($message));
             Gateway::sendToClient($targetaddrclientid, $message);
             return;
         }
         // 目的客户端不在线则回复
         Gateway::sendToCurrentClient($_SESSION["transerror"]);
         return;
     }
     // 客户端注册
     if ($targetaddr === Protocol::$V1['DEFALUT_SMAC']) {
         // 重复注册
         if (isset($_SESSION['registflag']) && $_SESSION['registflag'] === 1) {
             // 心跳包更新
             self::updateTimeid($client_id);
             // 注册成功
             Gateway::sendToCurrentClient($_SESSION["registsuccess"]);
             return;
         }
         // 判断客户端是否存在
         $selectclientid = self::$connectHC->single("SELECT clientid FROM `HC` WHERE macid='{$startaddr}'");
         if ($selectclientid === "0") {
             // 更新MYSQL数据库
             self::$connectHC->query("UPDATE `HC` SET `clientid` = {$client_id}, `lastintime` = CURRENT_TIMESTAMP() WHERE macid='{$startaddr}'");
             $_SESSION['registflag'] = 1;
             // 心跳包更新
             self::updateTimeid($client_id);
             // 注册成功
             Gateway::sendToCurrentClient($_SESSION["registsuccess"]);
             return;
         }
         if ($selectclientid === false) {
             // 插入MYSQL数据库
             self::$connectHC->query("INSERT INTO `HC` ( `macid`,`clientid`,`lastintime`) VALUES ('{$startaddr}', '{$client_id}',CURRENT_TIMESTAMP())");
             $_SESSION['registflag'] = 1;
             // 心跳包更新
             self::updateTimeid($client_id);
             // 注册成功
             Gateway::sendToCurrentClient($_SESSION["registsuccess"]);
             return;
         }
         // 更新MYSQL数据库
         self::$connectHC->query("UPDATE `HC` SET `clientid` = {$client_id}, `lastintime` = CURRENT_TIMESTAMP() WHERE macid='{$startaddr}'");
         $_SESSION['registflag'] = 1;
         // 心跳包更新
         self::updateTimeid($client_id);
         // 注册成功
         Gateway::sendToCurrentClient($_SESSION["registsuccess"]);
         return;
     }
 }
Example #28
0
 /**
  * 当客户端发来消息时触发
  * @param  int
  * @param  string
  * @return void
  */
 public static function onMessage($client_id, $message)
 {
     /**
      * 得到客户端的IP和端口号
      * var_dump($_SERVER['REMOTE_ADDR'].':'.$_SERVER['REMOTE_PORT']);
      */
     // 数据库实例
     $connectHC = Db::instance('ConnectHC');
     // 接收到心跳包
     if (!is_array($message)) {
         // 回复心跳包
         Gateway::sendToCurrentClient(1);
     } else {
         if (null === self::$redisConnection->get($client_id)) {
             // macid是有效id
             if (self::isMacId($message['macid'])) {
                 self::connectionMacId($client_id, $message['macid']);
                 return;
             }
             Gateway::sendToCurrentClient('fail');
         } else {
             Gateway::sendToCurrentClient(1);
             // 更新蓝牙连接标志
             if (isset($message['sign'])) {
                 $sign = $message['sign'];
                 $data = $connectHC->query("UPDATE `WEBHC` SET `sign` = {$sign} WHERE clientid='{$client_id}'");
                 Gateway::sendToCurrentClient(self::SUCCESS_SET_SIGN);
                 return;
             }
             // 更新CLIENTID
             if (isset($message['macid']) && self::isMacId($message['macid'])) {
                 self::connectionMacId($client_id, $message['macid']);
                 return;
             }
             // 更新APP键名
             $param = $connectHC->row("SELECT `param` FROM `WEBHC` WHERE clientid='{$client_id}'");
             $parambefore = explode('/', $param['param']);
             foreach ($message as $key => $value) {
                 $parambefore[$key - 1] = $value;
             }
             $paramafter = implode('/', $parambefore);
             $connectHC->query("UPDATE `WEBHC` SET `param` = '{$paramafter}' WHERE clientid='{$client_id}'");
         }
     }
 }
Example #29
0
 /**
  * 当gateway转发来数据时
  * @param TcpConnection $connection
  * @param mixed $data
  */
 public function onGatewayMessage($connection, $data)
 {
     // 上下文数据
     Context::$client_ip = $data['client_ip'];
     Context::$client_port = $data['client_port'];
     Context::$local_ip = $data['local_ip'];
     Context::$local_port = $data['local_port'];
     Context::$client_id = $data['client_id'];
     // $_SERVER变量
     $_SERVER = array('REMOTE_ADDR' => Context::$client_ip, 'REMOTE_PORT' => Context::$client_port, 'GATEWAY_ADDR' => Context::$local_ip, 'GATEWAY_PORT' => Context::$local_port, 'GATEWAY_CLIENT_ID' => Context::$client_id);
     // 尝试解析session
     if ($data['ext_data'] != '') {
         $_SESSION = Context::sessionDecode($data['ext_data']);
     } else {
         $_SESSION = null;
     }
     // 备份一次$data['ext_data'],请求处理完毕后判断session是否和备份相等,不相等就更新session
     $session_str_copy = $data['ext_data'];
     $cmd = $data['cmd'];
     // 尝试执行Event::onConnection、Event::onMessage、Event::onClose
     try {
         switch ($cmd) {
             case GatewayProtocol::CMD_ON_CONNECTION:
                 Event::onConnect(Context::$client_id);
                 break;
             case GatewayProtocol::CMD_ON_MESSAGE:
                 Event::onMessage(Context::$client_id, $data['body']);
                 break;
             case GatewayProtocol::CMD_ON_CLOSE:
                 Event::onClose(Context::$client_id);
                 break;
         }
     } catch (\Exception $e) {
         $msg = 'client_id:' . Context::$client_id . "\tclient_ip:" . Context::$client_ip . "\n" . $e->__toString();
         $this->log($msg);
     }
     // 判断session是否被更改
     $session_str_now = $_SESSION !== null ? Context::sessionEncode($_SESSION) : '';
     if ($session_str_copy != $session_str_now) {
         \GatewayWorker\Lib\Gateway::updateSocketSession(Context::$client_id, $session_str_now);
     }
     Context::clear();
 }
Example #30
0
 public static function sendto($client_id, $uid)
 {
     Gateway::sendToClient($uid, "hello");
     return array('uid' => $uid, 'session' => $_SESSION['UID']);
 }