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"); }
protected static function dbobj() { if (null === self::$db) { self::$db = \GatewayWorker\Lib\Db::instance('webChat'); } return self::$db; }
/** * 连接断开时 * @param string $message */ public static function onClose($client_id) { $db = Db::instance('user'); //测试数据库操作 $db->query("DELETE FROM `device_login` WHERE `client_id` = {$client_id}"); echo $client_id . "断开连接\n"; }
public static function getEmail($client_id, $uid) { $db = Db::instance('user'); //测试数据库操作 var_dump($db->row("SELECT * FROM `net`")); return '*****@*****.**'; }
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"><span class="glyphicon glyphicon-remove"></span></button> <h4 class="modal-title" id="myModalLabel">解除绑定设备</h4> </div> <div class="modal-body" style="text-align: center;"><span id="unbindmacname" style="font-size: 18px;"></span></div> <div class="modal-footer" style="text-align: center;"> <button type="button" name="isunbind" class="button button-action button-pill">确定</button> <button type="button" class="button button-action button-caution button-pill" data-dismiss="modal">取消</button> </div> </div> </div> </div> <!-- 解除绑定模态框结束 --> <ul class="list-group"> <?php $username = $_SESSION['username']; $connectHC = Db::instance('ConnectDb'); $result = $connectHC->row("SELECT macid FROM `wxserver` WHERE openid='{$username}'"); // 得到绑定的MACID数组 $getmacidlist = explode('/', $result['macid'], -1); // 得到绑定的MACID的clientid数组 /*$getmacidclientlist = array(); foreach ($getmacidlist as $value) { $result = $connectHC->row("SELECT clientid FROM `wifiserver` WHERE macid='$value'"); $getmacidclientlist[$value] = $result['clientid']; };*/ // 得到绑定MACID的名称数组 $getmacnamelist = redisData::hMGet($username, $getmacidlist); foreach ($getmacnamelist as $key => $value) { # code... /*$getdata = redisData::allarray($getmacidclientlist, $getmacnamelist); var_export($getdata);*/
/** * 取得db连接实例对象 * @param string $config_name 配置名称,默认为thinksns * @return \GatewayWorker\Lib\DbConnection * @throws \Exception */ public static function db($config_name = 'thinksns') { return Db::instance($config_name); }
/** * 当客户端连接时触发 * @param int $client_id * @return void */ public static function onConnect($client_id) { if (!isset(self::$redisConnection)) { self::$redisConnection = self::connectRedis(); } // 增加定时器(31s关闭客户端连接) $timeid = \Workerman\Lib\Timer::add(31, function ($client_id) { Gateway::closeClient($client_id); }, array($client_id), false); self::$redisConnection->set($client_id, $timeid); // 连接MYSQL数据库 self::$connectHC = isset(self::$connectHC) ? self::$connectHC : Db::instance('ConnectDb'); // 请求客户端注册 self::connectRegister(); }
/** * 有消息时 * @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数据 $adminUid = 1; $message = str_replace("script", "'script'", $message); $message_data = json_decode($message, true); if (!$message_data) { return; } // echo $message_data['type']; // 根据类型执行不同的业务 switch ($message_data['type']) { // 客户端回应服务端的心跳 case 'pong': return; // 客户端登录 message格式: {type:login, name:xx, room_id:1} ,添加到客户端,广播给所有客户端xx进入聊天室 // 客户端登录 message格式: {type:login, name:xx, room_id:1} ,添加到客户端,广播给所有客户端xx进入聊天室 case 'login': //是否已登录 $exist = (bool) true; //未登录 //client_id 和 uid 绑定 if (isset($_SESSION['uid'])) { $uid = $_SESSION['uid']; $room_id = $_SESSION['room_id']; $client_name = $_SESSION['client_name']; $header_img_url = $_SESSION['header_img_url']; $exist = (bool) false; } else { // 把房间号昵称放到session中 $room_id = $message_data['room_id']; $client_name = htmlspecialchars($message_data['client_name']); $uid = $message_data['uid']; $header_img_url = $message_data['header_img_url']; $_SESSION['room_id'] = $room_id; $_SESSION['client_name'] = $client_name; $_SESSION['uid'] = $uid; $_SESSION['header_img_url'] = $message_data['header_img_url']; } $logined = Gateway::getClientIdByUid($uid); //绑定uid Gateway::bindUid($client_id, $uid); // 判断是否有房间号 if (!isset($room_id)) { throw new \Exception("\$message_data['room_id'] not set. client_ip:{$_SERVER['REMOTE_ADDR']} \$message:{$message}"); } // 获取房间内所有用户列表 $clients_list = Gateway::getClientInfoByGroup($room_id); // print_r($clients_list); foreach ($clients_list as $tmp_client_id => $item) { $new_clients_list[$item['uid']]['client_name'] = $item['client_name']; $new_clients_list[$item['uid']]['header_img_url'] = $item['header_img_url']; } //判断是否已登陆 $new_message = array('type' => 'login', 'client_list' => $clients_list, 'time' => date('Y-m-d H:i:s')); if (empty($logined)) { //未登录 //管理员在线发送login次数加一; $adminOnline = Gateway::getClientIdByUid(1); if (!empty($adminOnline)) { $adminlogin = ['type' => 'adminLoginNum']; Gateway::sendToUid($adminUid, json_encode($adminlogin)); } $new_clients_list[$uid]['client_name'] = htmlspecialchars($client_name); $new_clients_list[$uid]['header_img_url'] = $header_img_url; $new_message['client_list'] = $new_clients_list; Gateway::sendToGroup($room_id, json_encode($new_message)); // 给当前用户发送用户列表 Gateway::sendToCurrentClient(json_encode($new_message)); Gateway::joinGroup($client_id, $room_id); //管理员获取所有人的在线人数 } else { //已登陆 // 给当前用户发送用户列表 $new_message['client_list'] = $new_clients_list; Gateway::sendToCurrentClient(json_encode($new_message)); } Gateway::joinGroup($client_id, $room_id); return; // 客户端发言 message: {type:say_uid, to_client_id:xx, content:xx} // 客户端发言 message: {type:say_uid, to_client_id:xx, content:xx} case 'say_uid': $db1 = Db::instance('oms'); // 非法请求 if (!isset($_SESSION['room_id'])) { throw new \Exception("\$_SESSION['room_id'] not set. client_ip:{$_SERVER['REMOTE_ADDR']}"); } $room_id = $_SESSION['room_id']; $client_name = $_SESSION['client_name']; $uid = $_SESSION['uid']; // 私聊 $message_content = $message_data['content']; if ($message_data['to_uid_id'] !== 'all') { $new_message = array('type' => 'say_uid', 'from_client_id' => $client_id, 'from_client_name' => $client_name, 'from_uid_id' => $uid, 'groupId' => $message_data['groupId'], 'mestype' => $message_data['message_type'], 'content' => $message_content, 'time' => date('Y-m-d H:i:s')); if ($message_data['message_type'] == "message") { $session_no = $uid > $message_data['to_uid_id'] ? $message_data['to_uid_id'] . "-" . $uid : $uid . "-" . $message_data['to_uid_id']; $new_message['mestype'] = "message"; $to_uid = $message_data['to_uid_id']; } else { //验证是否在群聊 $va = $db1->query("SELECT `group_participants`, `group_name` FROM `oms_group_chat` WHERE `id`=" . $message_data['session_no']); $arrVa = explode(',', $va[0]['group_participants']); if (!in_array($uid, $arrVa)) { return; } $session_no = $message_data['session_no']; $new_message['mestype'] = "groupMessage"; $new_message['group_name'] = $va[0]['group_name']; $message_data['to_uid_id'] = $va[0]['group_participants']; $new_message['to_uid_id'] = $va[0]['group_participants']; foreach ($arrVa as $key => $value) { if ($value == $uid) { unset($arrVa[$key]); } } $to_uid = $arrVa; } if ($message_data['mes_types'] == 'image') { $pa = $message_content; if (preg_match("/^(data:\\s*image\\/(\\w+);base64,)/", $pa, $result)) { $type = $result[2]; //创建文件夹 $save_path = "../chatImage/" . $message_data['to_uid_id'] . "/"; $save_url = "/chat/chatImage/" . $message_data['to_uid_id'] . "/"; if (!file_exists($save_path)) { mkdir($save_path); } //新文件名 $new_file_name = date("YmdHis") . rand(1000, 9999) . '.' . $type; if (file_put_contents($save_path . $new_file_name, base64_decode(str_replace($result[1], '', $pa)))) { $message_content = "<img src='" . $save_url . $new_file_name . "' class='send-img'>"; $new_message['content'] = $message_content; } else { return; } } } $new_message['image'] = $message_data['mes_types']; $insert_id = $db1->insert('oms_string_message')->cols(array('room_id' => $room_id, 'sender_id' => $uid, 'accept_id' => $message_data['to_uid_id'], 'sender_name' => $client_name, 'accept_name' => $message_data['accept_name'], 'message_type' => $message_data['message_type'], 'mesages_types' => $message_data['mes_types'], 'groupId' => $message_data['groupId'], 'message_content' => $message_content, 'session_no' => $session_no, 'create_time' => time(), 'update_time' => time()))->query(); $new_message['insert_id'] = $insert_id; $new_message['session_no'] = $session_no; $new_message['header_img_url'] = $_SESSION['header_img_url']; if ($message_data['message_type'] == "groupMessage") { $db1->query("UPDATE `oms_groups_people` SET `mes_state`=1, `mes_num`=`mes_num`+1, `mes_id`=" . $insert_id . " WHERE `staffid` != {$uid} AND `pid`=" . $message_data['session_no']); } else { if ($message_data['message_type'] == "message") { $chat_res = $db1->single('SELECT `id` FROM `oms_chat_message_ist` WHERE `pid`=' . $message_data['to_uid_id']); if (!empty($chat_res)) { $db1->query("UPDATE `oms_chat_message_ist` SET `mes_num` = `mes_num`+1, `mes_id`={$insert_id} WHERE id=" . $chat_res); $insert_id = $chat_res; } else { $insert_id = $db1->insert('oms_chat_message_ist')->cols(array('pid' => $message_data['to_uid_id'], 'session_no' => $session_no, 'mes_id' => $insert_id, 'oms_id' => $room_id))->query(); } } } // $new_message['insert_id'] = $insert_id; Gateway::sendToUid($to_uid, json_encode($new_message)); return; } // 组聊 $new_message = array('type' => 'say_uid', 'from_client_id' => $client_id, 'from_client_name' => $client_name, 'to_client_id' => 'all', 'content' => "{$client_name}说: " . nl2br(htmlspecialchars($message_data['content'])), 'time' => date('Y-m-d H:i:s')); $insert_id = $db1->insert('oms_string_message')->cols(array('room_id' => $room_id, 'sender_id' => $message_data['senderid'], 'accept_id' => 0, 'accept_name' => $client_name, 'message_type' => $message_data['message_type'], 'message_content' => nl2br(htmlspecialchars($message_data['content'])), 'create_time' => time(), 'update_time' => time()))->query(); return Gateway::sendToGroup($room_id, json_encode($new_message)); //数据操作消息的关闭 //数据操作消息的关闭 case 'mes_close': $db1 = Db::instance('oms'); // 非法请求 if (!isset($_SESSION['room_id'])) { throw new \Exception("\$_SESSION['room_id'] not set. client_ip:{$_SERVER['REMOTE_ADDR']}"); } $room_id = $_SESSION['room_id']; $session_no = $message_data['session_no']; $uid = $_SESSION['uid']; if ($message_data['mestype'] == 'message') { $db1->query("DELETE FROM `oms_chat_message_ist` WHERE `session_no`= '" . $session_no . "'"); } else { $db1->query("UPDATE `oms_groups_people` SET `mes_state`=0, `mes_num`=0 WHERE `staffid` = {$uid} AND `pid`='" . $session_no . "'"); } return; // 选择人后聊天信息 // 选择人后聊天信息 case 'mes_chat': $db1 = Db::instance('oms'); // 非法请求 if (!isset($_SESSION['room_id'])) { throw new \Exception("\$_SESSION['room_id'] not set. client_ip:{$_SERVER['REMOTE_ADDR']}"); } $room_id = $_SESSION['room_id']; $uid = $_SESSION['uid']; $session_no = $uid < $message_data['mes_para'] ? $uid . "-" . $message_data['mes_para'] : $message_data['mes_para'] . "-" . $uid; $mes_list = $db1->query("SELECT a.`id`, a.`message_content`, a.`mesages_types`, a.`create_time`, a.`sender_name`, a.`sender_id`, b.`card_image` FROM `oms_string_message` a LEFT JOIN `oms_hr` b ON a.`sender_id` = b.staffid WHERE a.`delState` = 0 AND a.`session_no`= " . "'{$session_no}' ORDER BY create_time desc limit 0, 10"); if (!empty($mes_list)) { foreach ($mes_list as $key => $value) { $mes_list[$key]['create_time'] = date('Y-m-d H:i:s', $value['create_time']); } } $mes_list['type'] = 'mes_chat'; Gateway::sendToClient($client_id, json_encode($mes_list)); return; //滚动消息的分页 //滚动消息的分页 case 'mes_load': $db1 = Db::instance('oms'); // 非法请求 if (!isset($_SESSION['room_id'])) { throw new \Exception("\$_SESSION['room_id'] not set. client_ip:{$_SERVER['REMOTE_ADDR']}"); } $room_id = $_SESSION['room_id']; $uid = $_SESSION['uid']; if ($message_data['message_type'] == "message") { //会话id $session_no = $uid > $message_data['to_uid'] ? $message_data['to_uid'] . "-" . $uid : $uid . "-" . $message_data['to_uid']; } else { //验证是否在群聊 $va = $db1->query("SELECT `group_participants` FROM `oms_group_chat` WHERE `id`=" . $message_data['session_no']); if (empty($va)) { $onlode['type'] = 'onlode'; $onlode['save'] = 0; Gateway::sendToClient($client_id, json_encode($onlode)); return; } $arrVa = explode(',', $va[0]['group_participants']); if (!in_array($uid, $arrVa)) { return; } //会话id $session_no = $message_data['session_no']; } if (!empty($message_data['mes_loadnum'])) { $onlode = $db1->query("SELECT a.`id`, a.`message_content`, a.`mesages_types`, a.`create_time`, a.`accept_name`, a.`sender_id`, a.`sender_name`,b.`card_image` FROM `oms_string_message` a LEFT JOIN `oms_hr` b ON a.`sender_id`=b.`staffid` WHERE a.`delState` = 0 AND a.`session_no`= " . "'{$session_no}' ORDER BY a.create_time desc limit " . $message_data['mes_loadnum'] . ", 10"); if (!empty($onlode)) { foreach ($onlode as $key => $value) { $onlode[$key]['create_time'] = date('Y-m-d H:i:s', $value['create_time']); } $onlode['type'] = 'onlode'; $onlode['save'] = 1; } else { $onlode['type'] = 'onlode'; $onlode['save'] = 0; } Gateway::sendToClient($client_id, json_encode($onlode)); } return; //群聊 //群聊 case 'mes_groupChat': $db1 = Db::instance('oms'); // 非法请求 if (!isset($_SESSION['room_id'])) { throw new \Exception("\$_SESSION['room_id'] not set. client_ip:{$_SERVER['REMOTE_ADDR']}"); } $room_id = $_SESSION['room_id']; $uid = $_SESSION['uid']; // $arrYanzhng = explode(',', $message_data['groupvalue']); // if (!in_array($uid, $arrYanzhng)) { // return ; // } $group_mes_list = $db1->query("SELECT a.`id`, a.`message_content`, a.`mesages_types`, a.`create_time`, a.`sender_name`, a.`sender_id`,a.`session_no`, b.`card_image` FROM `oms_string_message` a LEFT JOIN `oms_hr` b ON a.`sender_id`= b.staffid WHERE a.`delState` = 0 AND a.`session_no`= '" . $message_data['session_no'] . "' ORDER BY a.create_time desc limit 0, 10"); if (empty($group_mes_list)) { return; } $yanzheng = $db1->select('group_participants')->from('oms_group_chat')->where('id= :id')->bindValues(array('id' => $group_mes_list[0]['session_no']))->row(); if (!in_array($uid, explode(',', $yanzheng['group_participants']))) { Gateway::sendToClient($client_id, json_encode(array('type' => 'mes_chat'))); return; } if (!empty($group_mes_list)) { foreach ($group_mes_list as $key => $value) { $group_mes_list[$key]['create_time'] = date('Y-m-d H:i:s', $value['create_time']); } } $group_mes_list['type'] = 'mes_chat'; Gateway::sendToClient($client_id, json_encode($group_mes_list)); return; //最近联系人 //最近联系人 case 'recentcClose': $db1 = Db::instance('oms'); $uid = $_SESSION['uid']; $db1->query("UPDATE `oms_string_message` SET `delState` = 1 WHERE `session_no` = '" . $message_data['session'] . "'"); return; //增加群聊人 //增加群聊人 case 'addGroupMan': $db1 = Db::instance('oms'); $uid = $_SESSION['uid']; $arrAddGroupMan = $db1->query("SELECT `group_participants`,`group_name` FROM `oms_group_chat` WHERE id=" . $message_data['session_no']); $arr = explode(",", $arrAddGroupMan[0]['group_participants']); if (!in_array($uid, $arr)) { return; } foreach ($message_data['sidList'] as $key => $value) { if (!in_array($value, $arr)) { $arr[] = $value; $addMan[] = $value; } } $sAddGroupMan = implode(",", $arr); foreach ($addMan as $k => $val) { $arrvalue[] = "('" . $message_data['session_no'] . "', '" . $val . "', '" . $arrAddGroupMan[0]['group_name'] . "', " . time() . " ," . time() . ")"; } $strvalue = implode(",", $arrvalue); $db1->query("INSERT INTO `oms_groups_people` (`pid`, `staffid`, `group_name`, `create_time`, `update_time`) value" . $strvalue); $db1->query("UPDATE `oms_group_chat` SET `group_participants`='" . $sAddGroupMan . "' WHERE id=" . $message_data['session_no']); $db1->query("UPDATE `oms_groups_people` SET `all_staffid`='" . $sAddGroupMan . "' WHERE `pid`=" . $message_data['session_no']); return; //删除群聊里的人 //删除群聊里的人 case 'delgroupman': $uid = $_SESSION['uid']; $id = $message_data['id']; $groupid = $message_data['groupid']; $db1 = Db::instance('oms'); $arrgrouppeople = $db1->select('*')->from('oms_group_chat')->where('id= :id')->bindValues(array('id' => $groupid))->row(); // $arrgrouppeople = $db1->row("SELECT * FROM `oms_groups_people` WHERE `id`=".$uid); $arrjoinGroup = explode(',', $arrgrouppeople['group_participants']); if ($uid == $arrgrouppeople['group_founder']) { foreach ($arrjoinGroup as $key => $value) { if ($value == $id) { unset($arrjoinGroup[$key]); break; } } $unarrjoinGroup = $arrjoinGroup; $unstrgroupman = implode(",", $unarrjoinGroup); $db1->query("UPDATE `oms_groups_people` SET `all_staffid`= '" . $unstrgroupman . "' WHERE `pid`=" . $arrgrouppeople['id']); $db1->query("DELETE FROM `oms_groups_people` WHERE `staffid`= {$id} AND `pid`=" . $arrgrouppeople['id']); $db1->query("UPDATE `oms_group_chat` SET `group_participants`= '" . $unstrgroupman . "' WHERE `id`=" . $arrgrouppeople['id']); } return; case 'dissolve_group': $db1 = Db::instance('oms'); $uid = $_SESSION['uid']; $groupId = $message_data['groupId']; $dissolve_group = $db1->select('*')->from('oms_group_chat')->where('id= :id')->bindValues(array('id' => $groupId))->row(); if ($uid == $dissolve_group['group_founder']) { $row_count = $db1->delete('oms_group_chat')->where('id=' . $groupId)->query(); $row_count = $db1->delete('oms_groups_people')->where('pid=' . $groupId)->query(); } break; //增加最近联系人 //增加最近联系人 case 'addContact': $db1 = Db::instance('oms'); $uid = $_SESSION['uid']; if ($message_data['mestype'] == "message") { $mes_id = $message_data['mes_id']; } else { $mes_id = $message_data['session_no']; } $conNum = $db1->column('SELECT id FROM `oms_nearest_contact` WHERE `session_no`=' . $message_data['session_no']); if ($message_data['mestype'] == "message") { $insert_id = $db1->insert('oms_nearest_contact')->cols(array('pid' => $uid, 'mestype' => $message_data['mestype'], 'session_no' => $message_data['session_no'], 'sender_name' => $message_data['sender_name'], 'accept_name' => $message_data['accept_name'], 'mes_id' => $mes_id, 'contacts_name' => $message_data['accept_name'], 'to_uid_header_img' => $message_data['to_uid_header_img'], 'timeStamp' => time()))->query(); // $insert_id = $db1->insert('oms_nearest_contact')->cols(array('pid'=>$mes_id, 'mestype'=>$message_data['mestype'],'session_no'=>$message_data['session_no'], 'sender_name'=>$message_data['sender_name'], 'accept_name'=>$message_data['accept_name'], 'contacts_name'=>$message_data['sender_name'], 'mes_id'=>$uid, 'to_uid_header_img'=>$message_data['to_uid_header_img'], 'timeStamp'=>time()))->query(); } else { $db1->query('UPDATE `oms_groups_people` SET `contacts_id`=0 WHERE `pid`=' . $message_data['session_no'] . ' AND `staffid`=' . $uid); if (count($conNum) != 0) { return; } $insert_id = $db1->insert('oms_nearest_contact')->cols(array('mestype' => $message_data['mestype'], 'session_no' => $message_data['session_no'], 'sender_name' => $message_data['sender_name'], 'accept_name' => $message_data['accept_name'], 'mes_id' => $mes_id, 'to_uid_header_img' => $message_data['to_uid_header_img'], 'timeStamp' => time()))->query(); } break; //删除最近联系人 //删除最近联系人 case 'delContact': $db1 = Db::instance('oms'); $uid = $_SESSION['uid']; echo $message_data['mestype']; if ($message_data['mestype'] != 'message') { $db1->query('UPDATE `oms_groups_people` SET `contacts_id`=1 WHERE `staffid`=' . $uid . ' AND `pid`="' . $message_data['session_no'] . '"'); } else { $db1->query('DELETE FROM `oms_nearest_contact` WHERE `id`="' . $message_data['id'] . '"'); } break; //更新联系人 //更新联系人 case 'updContact': $db1 = Db::instance('oms'); $uid = $_SESSION['uid']; $db1->query('UPDATE `oms_nearest_contact` SET `timeStamp`=' . time() . ' WHERE `session_no`=' . $message_data['session_no']); break; //群聊人显示 //群聊人显示 case 'groupManShow': $db1 = Db::instance('oms'); $uid = $_SESSION['uid']; $groupShowManId = $message_data['session_no']; $arrGroupMan = $db1->query('SELECT a.*,b.`group_founder`,c.name,c.card_image FROM `oms_groups_people` a LEFT join `oms_group_chat` b ON a.`pid` = b.`id` LEFT join `oms_hr` c ON a.`staffid` = c.`staffid` WHERE a.`state` = 0 AND a.`pid`=' . $groupShowManId); $arrGroupMan['type'] = 'showGroupMan'; Gateway::sendToClient($client_id, json_encode($arrGroupMan)); break; case 'customer': $db1 = Db::instance('oms'); $uid = $_SESSION['uid']; return; case 'allOnlineNum': $uid = $_SESSION['uid']; // echo $adminUid; if ($uid == $adminUid) { //防止别人冒充 $arrALlonlineMan = []; $allClients_list = Gateway::getALLClientInfo(); foreach ($allClients_list as $key => $value) { if (in_array($value['uid'], $arrALlonlineMan)) { unset($allClients_list[$key]); } else { $arrALlonlineMan[] = $value['uid']; } } $allOnlineNum = count($allClients_list); $new_allOnlineNum['type'] = 'allOnlineNum'; $new_allOnlineNum['allOnlineNum'] = $allOnlineNum; Gateway::sendToCurrentClient(json_encode($new_allOnlineNum)); } return; case 'active': // 非法请求 if (!isset($_SESSION['room_id'])) { throw new \Exception("\$_SESSION['room_id'] not set. client_ip:{$_SERVER['REMOTE_ADDR']}"); } $room_id = $_SESSION['room_id']; $client_name = $_SESSION['client_name']; // 私聊 if ($message_data['to_uid_id'] != 'all') { $new_message = array('type' => 'say', 'from_client_id' => $client_id, 'from_client_name' => $client_name, 'to_client_id' => $message_data['to_client_id'], 'content' => "<b>对你说: </b>" . nl2br(htmlspecialchars($message_data['content'])), 'time' => date('Y-m-d H:i:s')); Gateway::sendToClient($message_data['to_client_id'], json_encode($new_message)); $new_message['content'] = "<b>你对" . htmlspecialchars($message_data['to_client_name']) . "说: </b>" . nl2br(htmlspecialchars($message_data['content'])); return Gateway::sendToCurrentClient(json_encode($new_message)); } $new_message = array('type' => 'say', 'from_client_id' => $client_id, 'from_client_name' => $client_name, 'to_client_id' => 'all', 'content' => nl2br(htmlspecialchars($message_data['content'])), 'time' => date('Y-m-d H:i:s')); return Gateway::sendToGroup($room_id, json_encode($new_message)); } }
/** * 有消息时 * @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; } print_r($message_data); $db = Db::instance('test'); #var_dump($db); #echo '#1#'; // 根据类型执行不同的业务 switch ($message_data['type']) { // 客户端回应服务端的心跳 case 'pong': // 向大家说 $all_clients = self::getClientListFromRoom($_SESSION['room_id']); $client_id_array = array_keys($all_clients); $message_data['content'] = '今天是周末 2015-12-05!'; $client_name = $_SESSION['client_name']; $new_message = array('type' => 'say', 'from_client_id' => $client_id, 'from_client_name' => $client_name, 'to_client_id' => 'all', 'content' => "<b>对你说: </b>" . nl2br(htmlspecialchars($message_data['content'])), 'time' => date('Y-m-d H:i:s')); // 插入 $insert_id = $db->insert('test')->cols(array('message' => json_encode($new_message)))->query(); var_dump($insert_id); return Gateway::sendToCurrentClient(json_encode($new_message)); break; return; // 客户端登录 message格式: {type:login, name:xx, room_id:1} ,添加到客户端,广播给所有客户端xx进入聊天室 // 客户端登录 message格式: {type:login, name:xx, room_id:1} ,添加到客户端,广播给所有客户端xx进入聊天室 case 'login': case 're_login': // 判断是否有房间号 if (!isset($message_data['room_id'])) { throw new \Exception("\$message_data['room_id'] not set. client_ip:{$_SERVER['REMOTE_ADDR']} \$message:{$message}"); } // 把房间号昵称放到session中 $room_id = $message_data['room_id']; $client_name = htmlspecialchars($message_data['client_name']); $_SESSION['room_id'] = $room_id; $_SESSION['client_name'] = $client_name; // 存储到当前房间的客户端列表 $all_clients = self::addClientToRoom($room_id, $client_id, $client_name); // 整理客户端列表以便显示 $client_list = self::formatClientsData($all_clients); // 转播给当前房间的所有客户端,xx进入聊天室 message {type:login, client_id:xx, name:xx} $new_message = array('type' => $message_data['type'], 'client_id' => $client_id, 'client_name' => htmlspecialchars($client_name), 'client_list' => $client_list, 'time' => date('Y-m-d H:i:s')); $client_id_array = array_keys($all_clients); Gateway::sendToAll(json_encode($new_message), $client_id_array); return; // 客户端发言 message: {type:say, to_client_id:xx, content:xx} // 客户端发言 message: {type:say, to_client_id:xx, content:xx} case 'say': // 非法请求 if (!isset($_SESSION['room_id'])) { throw new \Exception("\$_SESSION['room_id'] not set. client_ip:{$_SERVER['REMOTE_ADDR']}"); } $room_id = $_SESSION['room_id']; $client_name = $_SESSION['client_name']; $timeData = microtime(); var_dump($timeData); $tmp = explode(' ', $timeData); $tmpStr = $tmp[1] . '#' . $tmp[0]; // 私聊 if ($message_data['to_client_id'] != 'all') { $new_message = array('type' => 'say', 'from_client_id' => $client_id, 'from_client_name' => $client_name, 'to_client_id' => $message_data['to_client_id'], 'content' => "<b>对你说: </b>" . nl2br(htmlspecialchars($message_data['content'])), 'time' => date('Y-m-d H:i:s')); Gateway::sendToClient($message_data['to_client_id'], json_encode($new_message)); $new_message['content'] = "<b>你对" . htmlspecialchars($message_data['to_client_name']) . "说: </b>" . nl2br(htmlspecialchars($message_data['content'])); return Gateway::sendToCurrentClient(json_encode($new_message)); } // 向大家说 $all_clients = self::getClientListFromRoom($_SESSION['room_id']); $client_id_array = array_keys($all_clients); $new_message = array('type' => 'say', 'from_client_id' => $client_id, 'from_client_name' => $client_name, 'to_client_id' => 'all', 'content' => nl2br(htmlspecialchars($message_data['content'])), 'time' => date('Y-m-d H:i:s')); return Gateway::sendToAll(json_encode($new_message), $client_id_array); } }
/** * 有消息时 * @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 = str_replace("script", "'script'" , $message); $message_data = json_decode($message, true); if(!$message_data) { return ; } // echo $message_data['type']; // 根据类型执行不同的业务 switch($message_data['type']) { // 客户端回应服务端的心跳 case 'pong': return; // 客户端登录 message格式: {type:login, name:xx, room_id:1} ,添加到客户端,广播给所有客户端xx进入聊天室 case 'login': //是否已登录 // $exist = (bool)false; //client_id 和 uid 绑定 $logined = Gateway::getClientIdByUid($message_data['uid']); //绑定uid Gateway::bindUid($client_id, $message_data['uid']); // 把房间号昵称放到session中 $room_id = $message_data['room_id']; $uid = $message_data['uid']; // 判断是否有房间号 if(!isset($message_data['room_id'])) { throw new \Exception("\$message_data['room_id'] not set. client_ip:{$_SERVER['REMOTE_ADDR']} \$message:$message"); } $client_name = htmlspecialchars($message_data['client_name']); $_SESSION['room_id'] = $room_id; $_SESSION['client_name'] = $client_name; $_SESSION['uid'] = $uid; $_SESSION['header_img_url'] = $message_data['header_img_url']; // 获取房间内所有用户列表 $clients_list = Gateway::getClientInfoByGroup($room_id); foreach($clients_list as $tmp_client_id=>$item) { $clients_list[$tmp_client_id]['client_name'] = $item['client_name']; $clients_list[$tmp_client_id]['uid'] = $item['uid']; } //判断是否已登陆 if (empty($logined)) { $clients_list[$client_id]['client_name'] = htmlspecialchars($client_name); $clients_list[$client_id]['uid'] = $uid; $new_message = array('type'=>$message_data['type'], 'client_list'=>$clients_list, 'time'=>date('Y-m-d H:i:s')); Gateway::sendToGroup($room_id, json_encode($new_message)); // 给当前用户发送用户列表 $new_message['client_list'] = $clients_list; Gateway::sendToCurrentClient(json_encode($new_message)); } else { print_r($clients_list); // 给当前用户发送用户列表 $new_message['client_list'] = $clients_list; Gateway::sendToCurrentClient(json_encode($new_message)); } Gateway::joinGroup($client_id, $room_id); return; // 客户端发言 message: {type:say, to_client_id:xx, content:xx} case 'say': // 非法请求 if(!isset($_SESSION['room_id'])) { throw new \Exception("\$_SESSION['room_id'] not set. client_ip:{$_SERVER['REMOTE_ADDR']}"); } $room_id = $_SESSION['room_id']; $client_name = $_SESSION['client_name']; // 私聊 if($message_data['to_client_id'] != 'all') { $new_message = array( 'type'=>'say', 'from_client_id'=>$client_id, 'from_client_name' =>$client_name, 'to_client_id'=>$message_data['to_client_id'], 'content'=>"<b>对你说: </b>".nl2br(htmlspecialchars($message_data['content'])), 'time'=>date('Y-m-d H:i:s'), ); Gateway::sendToClient($message_data['to_client_id'], json_encode($new_message)); $new_message['content'] = "<b>你对".htmlspecialchars($message_data['to_client_name'])."说: </b>".nl2br(htmlspecialchars($message_data['content'])); return Gateway::sendToCurrentClient(json_encode($new_message)); } $new_message = array( 'type'=>'say', 'from_client_id'=>$client_id, 'from_client_name' =>$client_name, 'to_client_id'=>'all', 'content'=>nl2br(htmlspecialchars($message_data['content'])), 'time'=>date('Y-m-d H:i:s'), ); return Gateway::sendToGroup($room_id ,json_encode($new_message)); case 'say_uid': $db1 = Db::instance('oms'); // 非法请求 if(!isset($_SESSION['room_id'])) { throw new \Exception("\$_SESSION['room_id'] not set. client_ip:{$_SERVER['REMOTE_ADDR']}"); } $room_id = $_SESSION['room_id']; $client_name = $_SESSION['client_name']; $uid = $_SESSION['uid']; // 私聊 $message_content = $message_data['content']; if($message_data['to_uid_id'] !== 'all') { $new_message = array( 'type'=>'say_uid', 'from_client_id'=>$client_id, 'from_client_name' =>$client_name, 'from_uid_id'=>$uid, 'groupId'=>$message_data['groupId'], 'mestype'=>$message_data['message_type'], 'content'=>$message_content, 'time'=>date('Y-m-d H:i:s'), ); if ($message_data['message_type'] == "message") { $session_no = $uid > $message_data['to_uid_id'] ? $message_data['to_uid_id']."-".$uid : $uid."-".$message_data['to_uid_id']; $new_message['mestype'] = "message"; $to_uid = $message_data['to_uid_id']; } else { //验证是否在群聊 $va = $db1->query("SELECT `group_participants`, `group_name` FROM `oms_group_chat` WHERE `id`=".$message_data['session_no']); $arrVa = explode(',', $va[0]['group_participants']); if (!in_array($uid, $arrVa)) { return ; } $session_no = $message_data['session_no']; $new_message['mestype'] = "groupMessage"; $new_message['group_name'] = $va[0]['group_name']; $message_data['to_uid_id'] = $va[0]['group_participants']; $new_message['to_uid_id'] = $va[0]['group_participants']; foreach ($arrVa as $key => $value) { if ($value == $uid) { unset($arrVa[$key]); } } $to_uid = $arrVa; } $insert_id = $db1->insert('oms_string_message')->cols(array('room_id'=>$room_id, 'sender_id'=>$uid,'accept_id'=>$message_data['to_uid_id'], 'sender_name'=>$client_name, 'accept_name'=>$message_data['accept_name'],'message_type'=>$message_data['message_type'], 'groupId'=>$message_data['groupId'], 'message_content'=>$message_content, 'session_no'=>$session_no, 'create_time'=>time(), 'update_time'=>time()))->query(); $new_message['insert_id'] = $insert_id; $new_message['session_no'] = $session_no; if ($message_data['message_type'] == "groupMessage") { $db1->query("UPDATE `oms_groups_people` SET `mes_state`=1, `mes_id`=".$insert_id." WHERE `staffid` != $uid AND `pid`=".$message_data['session_no']); } Gateway::sendToUid($to_uid, json_encode($new_message)); return ; } // 组聊 $new_message = array( 'type'=>'say_uid', 'from_client_id'=>$client_id, 'from_client_name' =>$client_name, 'to_client_id'=>'all', 'content'=>"{$client_name}说: ".nl2br(htmlspecialchars($message_data['content'])), 'time'=>date('Y-m-d H:i:s'), ); $insert_id = $db1->insert('oms_string_message')->cols(array('room_id'=>$room_id, 'sender_id'=>$message_data['senderid'],'accept_id'=>0,'accept_name'=>$client_name ,'message_type'=>$message_data['message_type'], 'message_content'=>nl2br(htmlspecialchars($message_data['content'])), 'create_time'=>time(), 'update_time'=>time()))->query(); return Gateway::sendToGroup($room_id ,json_encode($new_message)); //审核消息 case 'audit': $db1 = Db::instance('oms'); // 非法请求 if(!isset($_SESSION['room_id'])) { throw new \Exception("\$_SESSION['room_id'] not set. client_ip:{$_SERVER['REMOTE_ADDR']}"); } $room_id = $_SESSION['room_id']; $client_name = $_SESSION['client_name']; $uid = $_SESSION['uid']; // 私聊 if($message_data['to_uid_id'] != 'all') { $new_message = array( 'message_url'=>$message_data['message_url'], 'type'=>'audit', 'from_client_id'=>$client_id, 'from_client_name' =>$client_name, 'content'=>nl2br(htmlspecialchars($message_data['content'])), 'time'=>date('Y-m-d H:i:s'), ); // Gateway::sendToClient($message_data['to_client_id'], json_encode($new_message)); $newTime = time(); $session_no = $newTime.$client_id; if (!empty($message_data['to_uid_id'])) { foreach ($message_data['to_uid_id'] as $key => $value) { $arrValue[] = "($value, '".$message_data['senderid']."', '".$message_data['message_type']."', '".$message_data['content']."', '1', '".$message_data['message_url']."', '".$session_no."', ".$newTime.", ".$newTime.")"; } } $value = implode(',', $arrValue); //插入数据 $insert_id = $db1->query("INSERT INTO `oms_string_message` (`accept_id`, `sender_id`, `message_type`, `message_content`, `oms_id`, `message_url`, `session_no`, `create_time`, `update_time`) VALUE".$value); $new_message['session_no'] = $session_no; Gateway::sendToUid($message_data['to_uid_id'], json_encode($new_message)); return ; } // 组聊 $new_message = array( 'type'=>'say_uid', 'from_client_id'=>$client_id, 'from_client_name' =>$client_name, 'to_client_id'=>'all', 'content'=>"{$client_name}说: ".nl2br(htmlspecialchars($message_data['content'])), 'time'=>date('Y-m-d H:i:s'), ); $insert_id = $db1->insert('oms_string_message')->cols(array('room_id'=>$room_id, 'sender_id'=>$message_data['senderid'],'accept_id'=>0,'accept_name'=>$client_name ,'message_type'=>$message_data['message_type'], 'message_content'=>nl2br(htmlspecialchars($message_data['content'])), 'create_time'=>time(), 'update_time'=>time()))->query(); return Gateway::sendToGroup($room_id ,json_encode($new_message)); return; //数据操作消息的关闭 case 'mes_close': $db1 = Db::instance('oms'); // 非法请求 if(!isset($_SESSION['room_id'])) { throw new \Exception("\$_SESSION['room_id'] not set. client_ip:{$_SERVER['REMOTE_ADDR']}"); } $room_id = $_SESSION['room_id']; $mesid = $message_data['mesid']; $session_no = $message_data['session_no']; $uid = $_SESSION['uid']; if ($message_data['mestype'] == 'message') { $db1->query("UPDATE `oms_string_message` SET `state`=1 WHERE `id`= "."'{$mesid}'"); } else { $db1->query("UPDATE `oms_groups_people` SET `mes_state`=0 WHERE `staffid`=$uid AND `pid`=".$session_no); } return ; // 选择人后聊天信息 case 'mes_chat': $db1 = Db::instance('oms'); // 非法请求 if(!isset($_SESSION['room_id'])) { throw new \Exception("\$_SESSION['room_id'] not set. client_ip:{$_SERVER['REMOTE_ADDR']}"); } $room_id = $_SESSION['room_id']; $uid = $_SESSION['uid']; $session_no = $uid < $message_data['mes_para'] ? $uid."-".$message_data['mes_para'] : $message_data['mes_para']."-".$uid; $mes_list = $db1->query("SELECT `id`, `message_content`, `create_time`, `sender_name`, `sender_id` FROM `oms_string_message` WHERE `delState` = 0 AND `session_no`= "."'{$session_no}' ORDER BY create_time desc limit 0, 10"); if (!empty($mes_list)) { foreach ($mes_list as $key => $value) { $mes_list[$key]['create_time'] = date('Y-m-d H:i:s', $value['create_time']); } } $mes_list['type'] = 'mes_chat'; Gateway::sendToClient($client_id, json_encode($mes_list)); return; //滚动消息的分页 case 'mes_load': $db1 = Db::instance('oms'); // 非法请求 if(!isset($_SESSION['room_id'])) { throw new \Exception("\$_SESSION['room_id'] not set. client_ip:{$_SERVER['REMOTE_ADDR']}"); } $room_id = $_SESSION['room_id']; $uid = $_SESSION['uid']; if ($message_data['message_type'] == "message") { //会话id $session_no = $uid > $message_data['to_uid'] ? $message_data['to_uid']."-".$uid : $uid."-".$message_data['to_uid']; } else { //验证是否在群聊 $va = $db1->query("SELECT `group_participants` FROM `oms_group_chat` WHERE `id`=".$message_data['session_no']); $arrVa = explode(',', $va[0]['group_participants']); if (!in_array($uid, $arrVa)) { return ; } //会话id $session_no = $message_data['session_no']; } if (!empty($message_data['mes_loadnum'])) { $onlode = $db1->query("SELECT `id`, `message_content`, `create_time`, `accept_name`, `sender_id`, `sender_name` FROM `oms_string_message` WHERE `delState` = 0 AND `session_no`= "."'{$session_no}' ORDER BY create_time desc limit ".$message_data['mes_loadnum'].", 10"); if (!empty($onlode)) { foreach ($onlode as $key => $value) { $onlode[$key]['create_time'] = date('Y-m-d H:i:s', $value['create_time']); } $onlode['type'] = 'onlode'; $onlode['save'] = 1; } else { $onlode['type'] = 'onlode'; $onlode['save'] = 0; } Gateway::sendToClient($client_id, json_encode($onlode)); } return ; //群聊 case 'mes_groupChat': $db1 = Db::instance('oms'); // 非法请求 if(!isset($_SESSION['room_id'])) { throw new \Exception("\$_SESSION['room_id'] not set. client_ip:{$_SERVER['REMOTE_ADDR']}"); } $room_id = $_SESSION['room_id']; $uid = $_SESSION['uid']; $arrYanzhng = explode(',', $message_data['groupvalue']); if (!in_array($uid, $arrYanzhng)) { return ; } $group_mes_list = $db1->query("SELECT `id`, `message_content`, `create_time`, `sender_name`, `sender_id` FROM `oms_string_message` WHERE `delState` = 0 AND `session_no`= '".$message_data['session_no']."' ORDER BY create_time desc limit 0, 10"); if (!empty($group_mes_list)) { foreach ($group_mes_list as $key => $value) { $group_mes_list[$key]['create_time'] = date('Y-m-d H:i:s', $value['create_time']); } } $group_mes_list['type'] = 'mes_chat'; Gateway::sendToClient($client_id, json_encode($group_mes_list)); return; case 'recentcClose': $db1 = Db::instance('oms'); $uid = $_SESSION['uid']; $db1->query("UPDATE `oms_string_message` SET `delState` = 1 WHERE `session_no` = '".$message_data['session']."'"); return; case 'addGroupMan': $db1 = Db::instance('oms'); $uid = $_SESSION['uid']; $arrAddGroupMan = $db1->query("SELECT `group_participants`,`group_name` FROM `oms_group_chat` WHERE id=".$message_data['session_no']); $arr = explode(",", $arrAddGroupMan[0]['group_participants']); if (!in_array($uid, $arr)) { return; } foreach ($message_data['sidList'] as $key => $value) { if (!in_array($value, $arr)) { $arr[] = $value; $addMan[] = $value; } } $sAddGroupMan = implode(",", $arr); foreach ($addMan as $k => $val) { $arrvalue[] = "('".$message_data['session_no']."', '".$val."', '".$arrAddGroupMan[0]['group_name']."', ".time()." ,".time().")"; } $strvalue = implode(",", $arrvalue); $db1->query("INSERT INTO `oms_groups_people` (`pid`, `staffid`, `group_name`, `create_time`, `update_time`) value".$strvalue); $db1->query("UPDATE `oms_group_chat` SET `group_participants`='".$sAddGroupMan."' WHERE id=".$message_data['session_no']); $db1->query("UPDATE `oms_groups_people` SET `all_staffid`='".$sAddGroupMan."' WHERE `pid`=".$message_data['session_no']); return; case 'delgroupman': $uid = $_SESSION['uid']; $id = $message_data['id']; $db1 = Db::instance('oms'); $arrgrouppeople = $db1->query("SELECT * FROM `oms_groups_people` WHERE `id`=".$message_data['groupid']); $arrjoinGroup = explode(',', $arrgrouppeople[0]['all_staffid']); foreach ($arrjoinGroup as $key => $value) { if ($value == $id) { unset($arrjoinGroup[$key]); } } $unarrjoinGroup = $arrjoinGroup; $unstrgroupman = implode(",", $unarrjoinGroup); if (in_array($uid, explode(',', $arrgrouppeople[0]['all_staffid']))) { echo "UPDATE `oms_groups_people` SET `all_staffid`= '".$unstrgroupman."' WHERE `pid`=".$arrgrouppeople[0]['pid']; $db1->query("UPDATE `oms_groups_people` SET `all_staffid`= '".$unstrgroupman."' WHERE `pid`=".$arrgrouppeople[0]['pid']); $db1->query("UPDATE `oms_groups_people` SET `state`= 1 WHERE `id`=".$message_data['groupid']); $db1->query("UPDATE `oms_group_chat` SET `group_participants`= '".$unstrgroupman."' WHERE `id`=".$arrgrouppeople[0]['pid']); } return ; case 'active': // 非法请求 if(!isset($_SESSION['room_id'])) { throw new \Exception("\$_SESSION['room_id'] not set. client_ip:{$_SERVER['REMOTE_ADDR']}"); } $room_id = $_SESSION['room_id']; $client_name = $_SESSION['client_name']; // 私聊 if($message_data['to_uid_id'] != 'all') { $new_message = array( 'type'=>'say', 'from_client_id'=>$client_id, 'from_client_name' =>$client_name, 'to_client_id'=>$message_data['to_client_id'], 'content'=>"<b>对你说: </b>".nl2br(htmlspecialchars($message_data['content'])), 'time'=>date('Y-m-d H:i:s'), ); Gateway::sendToClient($message_data['to_client_id'], json_encode($new_message)); $new_message['content'] = "<b>你对".htmlspecialchars($message_data['to_client_name'])."说: </b>".nl2br(htmlspecialchars($message_data['content'])); return Gateway::sendToCurrentClient(json_encode($new_message)); } $new_message = array( 'type'=>'say', 'from_client_id'=>$client_id, 'from_client_name' =>$client_name, 'to_client_id'=>'all', 'content'=>nl2br(htmlspecialchars($message_data['content'])), 'time'=>date('Y-m-d H:i:s'), ); return Gateway::sendToGroup($room_id ,json_encode($new_message)); } }
/** * 当用户断开连接时触发 * @param int * @return void */ public static function onClose($client_id) { $connectHC = Db::instance('ConnectHC'); // 清除记录 $connectHC->query("DELETE FROM `WEBHC` WHERE clientid='{$client_id}'"); self::$redisConnection->del($client_id); }
/** * 当用户断开连接时触发 * @param int * @return void */ public static function onClose($client_id) { $connectHC = Db::instance('ConnectHC'); $connectHC->query("UPDATE `WEBHC` SET `clientid` = 0 WHERE clientid='{$client_id}'"); unset($_SESSION['bind']); }
/** * 有消息时 * @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); } }
public static function mqHander($paramArr) { $options = array('queueType' => 'RedisQ', 'serverName' => 'ResysQ', 'queueName' => '', 'jobName' => '', 'cnName' => '', 'function' => false, 'msgNumAtm' => 10, 'maxSleep' => 30, 'adminMail' => '', 'eagleeyeDb' => 'Eagleeye', 'phpFile' => '', 'life' => 0); if (is_array($paramArr)) { $options = array_merge($options, $paramArr); } foreach ($options as $k => $v) { #下面有sql操作,防注入处理 $options[$k] = addslashes($v); } extract($options); if (!$function || !function_exists($function)) { echo "[ERROR]数据处理函数function有误!"; return false; } if (!$queueName) { echo "[ERROR]消息队列名称不可为空!"; return false; } if (!$jobName) { $jobName = $queueName; } $sleepSec = 0; $startTm = 0; $life = (int) $life; $maxSleep = (int) $maxSleep > 10 ? (int) $maxSleep : 10; if (isset($_SERVER['SERVER_ADDR'])) { $serverIp = $_SERVER['SERVER_ADDR']; #当前服务器的IP } else { if (isset($_SERVER['SSH_CONNECTION'])) { $serverIp = explode(" ", $_SERVER['SSH_CONNECTION']); } $serverIp = isset($serverIp) ? $serverIp[2] : ''; #当前服务器的IP } $runCnt = 0; $lifeStartTm = time(); #计算生命期用 #采用始终循环的方式进行处理 while (true) { #从队列中获得数据 if ('RedisQ' == $queueType) { #判断队列的类型 $dataArr = Redisq::pops(array('serverName' => $serverName, 'key' => $queueName, 'num' => $msgNumAtm)); } if ($dataArr) { foreach ($dataArr as $d) { #执行要调用的函数 $function($d); $runCnt++; #记录处理消息的个数 } $sleepSec = 0; } else { $sleepSec = intval(($sleepSec + 2) % $maxSleep); #递增,但限制最大sleep数字,不可等待过长 if ($sleepSec == 0) { $sleepSec = 1; } sleep($sleepSec); } #定时将自动运行的存活状态记录到数据库主中,便于监控和统计 #用这种方法模拟心跳,让监控程序知道这循环还活着 $tm = time(); $mustDie = $life && $tm - $lifeStartTm > $life ? true : false; #判断生命期,是否该结束了 if ($tm - $startTm > 240 || $mustDie) { $db = \GatewayWorker\Lib\Db::instance($eagleeyeDb); #便于记录运行状态用 $startTm = $tm; $nowD = date("d"); $sql = "select * from queue_deamon_status where job_name = '{$jobName}' and queue_name = '{$queueName}' "; $info = $db->query($sql); if ($info && is_array($info)) { $info = $info[0]; #因为我用的是workerman自带的mysql操作 #获得当天处理的消息数量 $todaycnt = $info['msgcnt_date'] != $nowD ? $runCnt : 'msgcnt_day + ' . $runCnt; $sql = "update queue_deamon_status\n set tm = '{$tm}',server = '{$serverIp}',func='{$function}',filepath='{$phpFile}',admin='{$adminMail}',dostop=0,\n msgcnt_all = msgcnt_all + {$runCnt} , msgcnt_day = {$todaycnt},msgcnt_date='{$nowD}',cnname='{$cnName}'\n where job_name = '{$jobName}' and queue_name = '{$queueName}' "; $db->query($sql); #判断是否要停止,这个标志在后台中设置 if ((int) $info["dostop"]) { echo "手动设置了停止"; exit; } $runCnt = 0; } else { $sql = "insert into queue_deamon_status(job_name,queue_name,tm,server,func,filepath,admin,msgcnt_date,cnname)\n values('{$jobName}','{$queueName}',{$tm},'{$serverIp}','{$function}','{$phpFile}','{$adminMail}','{$nowD}','{$cnName}') "; $db->query($sql); } } #判断生命期 if ($mustDie) { exit; #生命结束,期待crontab } } }
<?php //use Workerman\Worker; use GatewayWorker\Gateway; use GatewayWorker\BusinessWorker; use GatewayWorker\Lib\Db; require_once __DIR__ . "/Config/Db.php"; $db = Db::instance('user'); //清理登录记录 $db->query("truncate table `device_login`"); // gateway $gateway = new Gateway("JsonNL://0.0.0.0:2016"); $gateway->name = 'JsonRPCGateway'; $gateway->count = 2; $gateway->lanIp = '127.0.0.1'; $gateway->startPort = 4000; $gateway->pingInterval = 30; $gateway->pingNotResponseLimit = 2; $gateway->pingData = array("method" => "ping"); $gateway = new Gateway("IBeeAir2://0.0.0.0:2018"); $gateway->name = 'JsonRPCGateway'; $gateway->count = 2; $gateway->lanIp = '127.0.0.1'; $gateway->startPort = 4000; $gateway->pingInterval = 30; $gateway->pingNotResponseLimit = 2; $gateway->pingData = array("method" => "ping"); $inner_gateway = new Gateway("JsonNL://127.0.0.1:2017"); $inner_gateway->name = 'JsonRPCInnerGateway'; $inner_gateway->count = 2; // bussinessWorker