Pārlūkot izejas kodu

群聊由以前的ajax轮询升级为Workerman以WebSocket协议的即时聊天,聊天更及时,负载也更大

齐博 4 gadi atpakaļ
vecāks
revīzija
f8d9dde4c2

+ 1 - 1
application/common/controller/AdminBase.php

@@ -65,7 +65,7 @@ class AdminBase extends Base
         if($this->request->isPost() || $this->route[2]=='delete'){
             Action::write(); //操作日志
             //把缓存全清除
-            if($this->user['groupid']==3){
+            if($this->user['groupid']==3 && in_array($this->route[1], ['setting','sort','module','field','plugin','module','hook_plugin','hook','timedtask','admin_menu','member_menu','webmenu','group','sort_field'])){
                 \think\Hook::add('app_end', function(){
                     if (!defined('IN_PLUGIN')&&!defined('FORBID_CLEAR_CACHE')&&empty(cache('forbid_clear_cache'))) {
                         Cache::clear();

+ 90 - 0
application/common/fun/Gatewayclient.php

@@ -0,0 +1,90 @@
+<?php
+namespace app\common\fun;
+
+use GatewayClient\Gateway;
+
+class Gatewayclient{
+    
+    private static $other_server = true;    //是否使用其它服务端做中转
+    private static $server_url = 'https://x1.soyixia.net/ws_server.php';
+    private static $client_url = 'wss://x1.soyixia.net:2345'; //客户端请求端口
+    
+    public function __construct(){
+        Gateway::$registerAddress = '127.0.0.1:1234';   //服务端通信IP及端口
+        //self::$client_url = 'ws://127.0.0.1:2345';;
+    }
+    
+    public function client_url(){
+        return self::$client_url;
+    }
+    
+    /**
+     * 给当前用户群群发信息
+     * @param number $my_uid 当前用户自己的ID
+     * @param number $uid 负数是圈子ID,正数是私人聊天对方的UID
+     * @param string $json_msg 消息内容,必须是json格式的数据
+     */
+    public function send_to_group($my_uid=0,$uid=0,$json_msg=''){
+        if (is_array($json_msg)) {
+            $json_msg = json_encode($json_msg);
+        }
+        $group_key = $this->get_group_key($my_uid,$uid);
+        if (self::$other_server) {
+            $data = [
+                'type'=>'sendToGroup',
+                'uid'=>$uid,
+                'my_uid'=>$my_uid,
+                'group_key'=>$group_key,
+                'json_msg'=>$json_msg,
+            ];
+            $result = http_curl(self::$server_url,$data);
+        }else{
+            Gateway::sendToGroup($group_key,$json_msg);
+            $all_json_msg = json_encode([
+                'type'=>'msglist',
+                'uid'=>$uid,
+                'from_uid'=>$my_uid,
+            ]);
+            Gateway::sendToAll($all_json_msg);  //提醒所有用户需要更新列表数据.客户端可以根据$uid做判断是否需要更新
+        }
+    }
+    
+    /**
+     * 把当前用户加入群发组
+     * @param number $my_uid 当前用户自己的ID
+     * @param number $uid 负数是圈子ID,正数是私人聊天对方的UID
+     * @param string $client_id WS生成的客户ID
+     */
+    public function user_join_group($my_uid=0,$uid=0,$client_id=''){        
+        $group_key = $this->get_group_key($my_uid,$uid);        
+        if (self::$other_server) {
+            $data = [
+                'type'=>'joinGroup',
+                'group_key'=>$group_key,
+                'client_id'=>$client_id,
+            ];
+            $result = http_curl(self::$server_url,$data);
+        }else{
+            Gateway::joinGroup($client_id,$group_key);
+        }
+    }
+    
+    /**
+     * 获取用户组的区分关键字
+     * @param number $my_uid 当前用户自己的ID
+     * @param number $uid 负数是圈子ID,正数是私人聊天对方的UID
+     */
+    public function get_group_key($my_uid=0,$uid=0){
+        static $webkey = null;
+        if(empty($webkey)){
+            $webkey = substr(md5_file(APP_PATH.'database.php'),5,10);
+        }
+        $group_key = $webkey.'__';
+        if ($uid<0) {   //代表是圈子
+            $group_key .= 'qun'.abs($uid);
+        }else{
+            $group_key .= 'msg'.($my_uid*$uid+$my_uid+$uid);
+        }
+        return $group_key;
+    }
+}

+ 1 - 0
application/common/upgrade/log76.txt

@@ -0,0 +1 @@
+群聊由以前的ajax轮询升级为Workerman以WebSocket协议的即时聊天,聊天更及时,负载也更大

+ 4 - 1
application/index/controller/Index.php

@@ -2,7 +2,7 @@
 namespace app\index\controller;
 
 use app\common\controller\IndexBase;
-
+use GatewayClient\Gateway;
 
 class Index extends IndexBase
 {
@@ -29,6 +29,9 @@ class Index extends IndexBase
     }
     
     public function test($page=1){
+        touch(RUNTIME_PATH.'Task.txt', time()-3600);
+        $ck_time = filemtime(RUNTIME_PATH.'Task.txt');
+        ECHO date('Y-m-d H:i:s',$ck_time);
         /*
         set_time_limit(0);
         $ck = 0;

+ 22 - 4
application/index/controller/wxapp/Msg.php

@@ -11,6 +11,21 @@ class Msg extends IndexBase{
         return $this->ok_js();
     }
     
+    /**
+     * 设置当前用户的群发消息组
+     * @param number $uid 负数是圈子ID,正数是私聊时对方的UID
+     * @param string $client_id WS生成的客户ID
+     */
+    public function bind_group($uid=0,$client_id=''){
+        if (empty($uid)) {
+            return $this->err_js('用户UID或者圈子ID不存在');
+        }elseif (empty($client_id)) {
+            return $this->err_js('客户ID不存在');
+        }
+        fun("Gatewayclient@user_join_group",$this->user['uid'],$uid,$client_id);
+        return $this->ok_js();
+    }
+    
     /**
      * 获取某个人跟它人或者是圈子的会话记录
      * @param number $uid 正数用户UID,负数圈子ID
@@ -29,7 +44,7 @@ class Msg extends IndexBase{
             if(!modules_config('qun')){
                 return $this->err_js('你没有安装圈子模块!');
             }
-            if($maxid<1){
+            if($maxid<1){   //首次加载
                 $qun_info = \app\qun\model\Content::getInfoByid(abs($uid),true);
                 if ($this->user) {
                     $qun_user = \app\qun\model\Member::where([
@@ -48,6 +63,7 @@ class Msg extends IndexBase{
                 }
             }
         }
+        
         $array = model::list_moremsg($this->user['uid'],$uid,$id,$rows,$maxid);
         $array['qun_info'] = $qun_info;
         $array['qun_userinfo'] = $qun_user;
@@ -63,6 +79,10 @@ class Msg extends IndexBase{
             $array['userinfo'] = ['uid'=>0,'username'=>'游客','groupid'=>0];
         }
         
+        if ($maxid<1) { //首次加载
+            $array['ws_url'] = fun('Gatewayclient@client_url'); //APP要用到
+        }
+        
         if ($is_live) {
 //             $live_array = cache('live_qun');
 //             $data = $this->request->post();
@@ -77,13 +97,11 @@ class Msg extends IndexBase{
 //             ];
 //             cache('live_qun',$live_array);
         }elseif($uid<1){    //代表群聊
-            $live_array = cache('live_qun');
+            $live_array = cache('live_qun');    //这里有个BUG,如果进后台操作过东西,缓存就会被清空,导致这里没数据
             if($live_array['qun'.$uid]){
                 $live_array['qun'.$uid]['time'] = 0;    //此参数将弃用
                 $live_array['qun'.$uid]['push_url']='';
                 $array['live_video'] = $live_array['qun'.$uid];
-            }else{
-                $live_array['qun'.$uid]['time'] = 100;//此参数将弃用
             }
         }        
         return $this->ok_js($array);

+ 25 - 3
application/member/controller/wxapp/Msg.php

@@ -202,6 +202,7 @@ class Msg extends MemberBase
             if($data['ext_sys'] && !is_numeric($data['ext_sys'])){
                 $data['ext_sys'] = modules_config($data['ext_sys'])['id'];
             }
+            $post_uid = $data['uid'];   //后面这个值$data['uid']会变动
             if ($data['uid']<0) {   //圈子群聊
                 $qun_id = abs($data['uid']);
                 $info = fun('qun@getByid',$qun_id);
@@ -218,6 +219,7 @@ class Msg extends MemberBase
                 ]);
                 Model::where('qun_id',$qun_id)->update(['update_time'=>time()]);    //其它人的群聊消息方便排在前面
             }else{
+                //这里有点BUG,如果用户名是数字的话,偶尔会冲突
                 $info = $data['uid'] ? get_user($data['uid']) : get_user($data['touser'],'username');
                 if (!$info) {
                     return $this->err_js('该用户不存在!');
@@ -227,11 +229,11 @@ class Msg extends MemberBase
                 }
                 $data['touid'] = $info['uid'];
             }      
-            $data['uid'] = $this->user['uid'];  //注意这里 uid值重新恢复到用户的UID
+            $data['uid'] = $this->user['uid'];  //务必高度注意这里 uid值变成了当前用户自己的ID,不再是对方的ID
             $data['content'] = fun('Filter@str',$data['content']);            
             //$data['content'] = str_replace(["\n",' '],['<br>','&nbsp;'],filtrate($data['content']));
             $result = Model::add($data,$this->admin);
-            if(is_numeric($result)){
+            if(is_numeric($result)){    //发送成功
                 $content = $this->user['username'] . ' 给你发了一条私信,请尽快查收,<a href="'.get_url(urls('member/msg/show',['id'=>$result])).'">点击查收</a>';
                 if(empty($qun_id)){
                     $info['weixin_api'] && send_wx_msg($info['weixin_api'], $content);
@@ -246,7 +248,27 @@ class Msg extends MemberBase
                         }                        
                     }
                 }
-                return $this->ok_js();
+                
+                $msginfo = [];
+                //$msginfo = [getArray(Model::get($result))]; //推数据
+                $msg_array = [
+                    'type'=>'newmsg',
+                    'data'=>$msginfo,
+                ];
+                $msg_array['ext']['maxid'] = $result;
+                if ($post_uid<0) {//代表群聊
+                    $live_array = cache('live_qun');    //这里有个BUG,如果进后台操作过东西,缓存就会被清空,导致这里没数据
+                    if($live_array['qun'.$post_uid]){
+                        $live_array['qun'.$post_uid]['time'] = 0;    //此参数将弃用
+                        $live_array['qun'.$post_uid]['push_url']='';
+                        $msg_array['ext']['live_video'] = $live_array['qun'.$post_uid];
+                    }
+                }
+                
+                fun("Gatewayclient@send_to_group",$this->user['uid'],$post_uid,$msg_array);     //同时通知其它客户
+                
+                return $this->ok_js($msg_array);
+                
             }elseif($result['errmsg']){
                 return $this->err_js($result['errmsg']);
             }else{

+ 1509 - 0
extend/GatewayClient/Gateway.php

@@ -0,0 +1,1509 @@
+<?php
+namespace GatewayClient;
+use \Exception;
+/**
+ * This file is part of workerman.
+ *
+ * Licensed under The MIT License
+ * For full copyright and license information, please see the MIT-LICENSE.txt
+ * Redistributions of files must retain the above copyright notice.
+ *
+ * @author walkor<walkor@workerman.net>
+ * @copyright walkor<walkor@workerman.net>
+ * @link http://www.workerman.net/
+ * @license http://www.opensource.org/licenses/mit-license.php MIT License
+ */
+/**
+ * 数据发送相关
+ * @version 3.0.12
+ */
+/**
+ * 数据发送相关
+ */
+class Gateway
+{
+    /**
+     * gateway 实例
+     *
+     * @var object
+     */
+    protected static $businessWorker = null;
+    /**
+     * 注册中心地址
+     *
+     * @var string|array
+     */
+    public static $registerAddress = '127.0.0.1:1236';
+    /**
+     * 秘钥
+     * @var string
+     */
+    public static $secretKey = '';
+    /**
+     * 链接超时时间
+     * @var int
+     */
+    public static $connectTimeout = 3;
+    /**
+     * 与Gateway是否是长链接
+     * @var bool
+     */
+    public static $persistentConnection = false;
+    
+    /**
+     * 向所有客户端连接(或者 client_id_array 指定的客户端连接)广播消息
+     *
+     * @param string $message           向客户端发送的消息
+     * @param array  $client_id_array   客户端 id 数组
+     * @param array  $exclude_client_id 不给这些client_id发
+     * @param bool   $raw               是否发送原始数据(即不调用gateway的协议的encode方法)
+     * @return void
+     * @throws Exception
+     */
+    public static function sendToAll($message, $client_id_array = null, $exclude_client_id = null, $raw = false)
+    {
+        $gateway_data         = GatewayProtocol::$empty;
+        $gateway_data['cmd']  = GatewayProtocol::CMD_SEND_TO_ALL;
+        $gateway_data['body'] = $message;
+        if ($raw) {
+            $gateway_data['flag'] |= GatewayProtocol::FLAG_NOT_CALL_ENCODE;
+        }
+        if ($exclude_client_id) {
+            if (!is_array($exclude_client_id)) {
+                $exclude_client_id = array($exclude_client_id);
+            }
+            if ($client_id_array) {
+                $exclude_client_id = array_flip($exclude_client_id);
+            }
+        }
+        if ($client_id_array) {
+            if (!is_array($client_id_array)) {
+                echo new \Exception('bad $client_id_array:'.var_export($client_id_array, true));
+                return;
+            }
+            $data_array = array();
+            foreach ($client_id_array as $client_id) {
+                if (isset($exclude_client_id[$client_id])) {
+                    continue;
+                }
+                $address = Context::clientIdToAddress($client_id);
+                if ($address) {
+                    $key                                         = long2ip($address['local_ip']) . ":{$address['local_port']}";
+                    $data_array[$key][$address['connection_id']] = $address['connection_id'];
+                }
+            }
+            foreach ($data_array as $addr => $connection_id_list) {
+                $the_gateway_data             = $gateway_data;
+                $the_gateway_data['ext_data'] = json_encode(array('connections' => $connection_id_list));
+                static::sendToGateway($addr, $the_gateway_data);
+            }
+            return;
+        } elseif (empty($client_id_array) && is_array($client_id_array)) {
+            return;
+        }
+        if (!$exclude_client_id) {
+            return static::sendToAllGateway($gateway_data);
+        }
+        $address_connection_array = static::clientIdArrayToAddressArray($exclude_client_id);
+        // 如果有businessWorker实例,说明运行在workerman环境中,通过businessWorker中的长连接发送数据
+        if (static::$businessWorker) {
+            foreach (static::$businessWorker->gatewayConnections as $address => $gateway_connection) {
+                $gateway_data['ext_data'] = isset($address_connection_array[$address]) ?
+                    json_encode(array('exclude'=> $address_connection_array[$address])) : '';
+                /** @var TcpConnection $gateway_connection */
+                $gateway_connection->send($gateway_data);
+            }
+        } // 运行在其它环境中,通过注册中心得到gateway地址
+        else {
+            $all_addresses = static::getAllGatewayAddressesFromRegister();
+            foreach ($all_addresses as $address) {
+                $gateway_data['ext_data'] = isset($address_connection_array[$address]) ?
+                    json_encode(array('exclude'=> $address_connection_array[$address])) : '';
+                static::sendToGateway($address, $gateway_data);
+            }
+        }
+    }
+    /**
+     * 向某个client_id对应的连接发消息
+     *
+     * @param int    $client_id
+     * @param string $message
+     * @return void
+     */
+    public static function sendToClient($client_id, $message)
+    {
+        return static::sendCmdAndMessageToClient($client_id, GatewayProtocol::CMD_SEND_TO_ONE, $message);
+    }
+    /**
+     * 判断某个uid是否在线
+     *
+     * @param string $uid
+     * @return int 0|1
+     */
+    public static function isUidOnline($uid)
+    {
+        return (int)static::getClientIdByUid($uid);
+    }
+    
+    /**
+     * 判断client_id对应的连接是否在线
+     *
+     * @param int $client_id
+     * @return int 0|1
+     */
+    public static function isOnline($client_id)
+    {
+        $address_data = Context::clientIdToAddress($client_id);
+        if (!$address_data) {
+            return 0;
+        }
+        $address      = long2ip($address_data['local_ip']) . ":{$address_data['local_port']}";
+        if (isset(static::$businessWorker)) {
+            if (!isset(static::$businessWorker->gatewayConnections[$address])) {
+                return 0;
+            }
+        }
+        $gateway_data                  = GatewayProtocol::$empty;
+        $gateway_data['cmd']           = GatewayProtocol::CMD_IS_ONLINE;
+        $gateway_data['connection_id'] = $address_data['connection_id'];
+        return (int)static::sendAndRecv($address, $gateway_data);
+    }
+    /**
+     * 获取所有在线用户的session,client_id为 key(弃用,请用getAllClientSessions代替)
+     *
+     * @param string $group
+     * @return array
+     */
+    public static function getAllClientInfo($group = '')
+    {
+        echo "Warning: Gateway::getAllClientInfo is deprecated and will be removed in a future, please use Gateway::getAllClientSessions instead.";
+        return static::getAllClientSessions($group);
+    }
+    /**
+     * 获取所有在线client_id的session,client_id为 key
+     *
+     * @param string $group
+     * @return array
+     */
+    public static function getAllClientSessions($group = '')
+    {
+        $gateway_data = GatewayProtocol::$empty;
+        if (!$group) {
+            $gateway_data['cmd']      = GatewayProtocol::CMD_GET_ALL_CLIENT_SESSIONS;
+        } else {
+            $gateway_data['cmd']      = GatewayProtocol::CMD_GET_CLIENT_SESSIONS_BY_GROUP;
+            $gateway_data['ext_data'] = $group;
+        }
+        $status_data      = array();
+        $all_buffer_array = static::getBufferFromAllGateway($gateway_data);
+        foreach ($all_buffer_array as $local_ip => $buffer_array) {
+            foreach ($buffer_array as $local_port => $data) {
+                if ($data) {
+                    foreach ($data as $connection_id => $session_buffer) {
+                        $client_id = Context::addressToClientId($local_ip, $local_port, $connection_id);
+                        if ($client_id === Context::$client_id) {
+                            $status_data[$client_id] = (array)$_SESSION;
+                        } else {
+                            $status_data[$client_id] = $session_buffer ? Context::sessionDecode($session_buffer) : array();
+                        }
+                    }
+                }
+            }
+        }
+        return $status_data;
+    }
+    /**
+     * 获取某个组的连接信息(弃用,请用getClientSessionsByGroup代替)
+     *
+     * @param string $group
+     * @return array
+     */
+    public static function getClientInfoByGroup($group)
+    {
+        echo "Warning: Gateway::getClientInfoByGroup is deprecated and will be removed in a future, please use Gateway::getClientSessionsByGroup instead.";
+        return static::getAllClientSessions($group);
+    }
+    /**
+     * 获取某个组的所有client_id的session信息
+     *
+     * @param string $group
+     *
+     * @return array
+     */
+    public static function getClientSessionsByGroup($group)
+    {
+        if (static::isValidGroupId($group)) {
+            return static::getAllClientSessions($group);
+        }
+        return array();
+    }
+    /**
+     * 获取所有在线client_id数
+     *
+     * @return int
+     */
+    public static function getAllClientIdCount()
+    {
+        return static::getClientCountByGroup();
+    }
+    /**
+     * 获取所有在线client_id数(getAllClientIdCount的别名)
+     *
+     * @return int
+     */
+    public static function getAllClientCount()
+    {
+        return static::getAllClientIdCount();
+    }
+    /**
+     * 获取某个组的在线client_id数
+     *
+     * @param string $group
+     * @return int
+     */
+    public static function getClientIdCountByGroup($group = '')
+    {
+        $gateway_data             = GatewayProtocol::$empty;
+        $gateway_data['cmd']      = GatewayProtocol::CMD_GET_CLIENT_COUNT_BY_GROUP;
+        $gateway_data['ext_data'] = $group;
+        $total_count              = 0;
+        $all_buffer_array         = static::getBufferFromAllGateway($gateway_data);
+        foreach ($all_buffer_array as $local_ip => $buffer_array) {
+            foreach ($buffer_array as $local_port => $count) {
+                if ($count) {
+                    $total_count += $count;
+                }
+            }
+        }
+        return $total_count;
+    }
+    /**
+     * getClientIdCountByGroup 函数的别名
+     *
+     * @param string $group
+     * @return int
+     */
+    public static function getClientCountByGroup($group = '')
+    {
+        return static::getClientIdCountByGroup($group);
+    }
+    /**
+     * 获取某个群组在线client_id列表
+     *
+     * @param string $group
+     * @return array
+     */
+    public static function getClientIdListByGroup($group)
+    {
+        if (!static::isValidGroupId($group)) {
+            return array();
+        }
+        $data = static::select(array('uid'), array('groups' => is_array($group) ? $group : array($group)));
+        $client_id_map = array();
+        foreach ($data as $local_ip => $buffer_array) {
+            foreach ($buffer_array as $local_port => $items) {
+                //$items = ['connection_id'=>['uid'=>x, 'group'=>[x,x..], 'session'=>[..]], 'client_id'=>[..], ..];
+                foreach ($items as $connection_id => $info) {
+                    $client_id = Context::addressToClientId($local_ip, $local_port, $connection_id);
+                    $client_id_map[$client_id] = $client_id;
+                }
+            }
+        }
+        return $client_id_map;
+    }
+    /**
+     * 获取集群所有在线client_id列表
+     *
+     * @return array
+     */
+    public static function getAllClientIdList()
+    {
+        return static::formatClientIdFromGatewayBuffer(static::select(array('uid')));
+    }
+    /**
+     * 格式化client_id
+     *
+     * @param $data
+     * @return array
+     */
+    protected static function formatClientIdFromGatewayBuffer($data)
+    {
+        $client_id_list = array();
+        foreach ($data as $local_ip => $buffer_array) {
+            foreach ($buffer_array as $local_port => $items) {
+                //$items = ['connection_id'=>['uid'=>x, 'group'=>[x,x..], 'session'=>[..]], 'client_id'=>[..], ..];
+                foreach ($items as $connection_id => $info) {
+                    $client_id = Context::addressToClientId($local_ip, $local_port, $connection_id);
+                    $client_id_list[$client_id] = $client_id;
+                }
+            }
+        }
+        return $client_id_list;
+    }
+    /**
+     * 获取与 uid 绑定的 client_id 列表
+     *
+     * @param string $uid
+     * @return array
+     */
+    public static function getClientIdByUid($uid)
+    {
+        $gateway_data             = GatewayProtocol::$empty;
+        $gateway_data['cmd']      = GatewayProtocol::CMD_GET_CLIENT_ID_BY_UID;
+        $gateway_data['ext_data'] = $uid;
+        $client_list              = array();
+        $all_buffer_array         = static::getBufferFromAllGateway($gateway_data);
+        foreach ($all_buffer_array as $local_ip => $buffer_array) {
+            foreach ($buffer_array as $local_port => $connection_id_array) {
+                if ($connection_id_array) {
+                    foreach ($connection_id_array as $connection_id) {
+                        $client_list[] = Context::addressToClientId($local_ip, $local_port, $connection_id);
+                    }
+                }
+            }
+        }
+        return $client_list;
+    }
+    /**
+     * 获取某个群组在线uid列表
+     *
+     * @param string $group
+     * @return array
+     */
+    public static function getUidListByGroup($group)
+    {
+        if (!static::isValidGroupId($group)) {
+            return array();
+        }
+        $group = is_array($group) ? $group : array($group);
+        $data = static::select(array('uid'), array('groups' => $group));
+        $uid_map = array();
+        foreach ($data as $local_ip => $buffer_array) {
+            foreach ($buffer_array as $local_port => $items) {
+                //$items = ['connection_id'=>['uid'=>x, 'group'=>[x,x..], 'session'=>[..]], 'client_id'=>[..], ..];
+                foreach ($items as $connection_id => $info) {
+                    if (!empty($info['uid'])) {
+                        $uid_map[$info['uid']] = $info['uid'];
+                    }
+                }
+            }
+        }
+        return $uid_map;
+    }
+    /**
+     * 获取某个群组在线uid数
+     *
+     * @param string $group
+     * @return int
+     */
+    public static function getUidCountByGroup($group)
+    {
+        if (static::isValidGroupId($group)) {
+            return count(static::getUidListByGroup($group));
+        }
+        return 0;
+    }
+    /**
+     * 获取全局在线uid列表
+     *
+     * @return array
+     */
+    public static function getAllUidList()
+    {
+        $data = static::select(array('uid'));
+        $uid_map = array();
+        foreach ($data as $local_ip => $buffer_array) {
+            foreach ($buffer_array as $local_port => $items) {
+                //$items = ['connection_id'=>['uid'=>x, 'group'=>[x,x..], 'session'=>[..]], 'client_id'=>[..], ..];
+                foreach ($items as $connection_id => $info) {
+                    if (!empty($info['uid'])) {
+                        $uid_map[$info['uid']] = $info['uid'];
+                    }
+                }
+            }
+        }
+        return $uid_map;
+    }
+    /**
+     * 获取全局在线uid数
+     * @return int
+     */
+    public static function getAllUidCount()
+    {
+        return count(static::getAllUidList());
+    }
+    /**
+     * 通过client_id获取uid
+     *
+     * @param $client_id
+     * @return mixed
+     */
+    public static function getUidByClientId($client_id)
+    {
+        $data = static::select(array('uid'), array('client_id'=>array($client_id)));
+        foreach ($data as $local_ip => $buffer_array) {
+            foreach ($buffer_array as $local_port => $items) {
+                //$items = ['connection_id'=>['uid'=>x, 'group'=>[x,x..], 'session'=>[..]], 'client_id'=>[..], ..];
+                foreach ($items as $info) {
+                    return $info['uid'];
+                }
+            }
+        }
+    }
+    /**
+     * 获取所有在线的群组id
+     *
+     * @return array
+     */
+    public static function getAllGroupIdList()
+    {
+        $gateway_data             = GatewayProtocol::$empty;
+        $gateway_data['cmd']      = GatewayProtocol::CMD_GET_GROUP_ID_LIST;
+        $group_id_list            = array();
+        $all_buffer_array         = static::getBufferFromAllGateway($gateway_data);
+        foreach ($all_buffer_array as $local_ip => $buffer_array) {
+            foreach ($buffer_array as $local_port => $group_id_array) {
+                if (is_array($group_id_array)) {
+                    foreach ($group_id_array as $group_id) {
+                        if (!isset($group_id_list[$group_id])) {
+                            $group_id_list[$group_id] = $group_id;
+                        }
+                    }
+                }
+            }
+        }
+        return $group_id_list;
+    }
+    /**
+     * 获取所有在线分组的uid数量,也就是每个分组的在线用户数
+     *
+     * @return array
+     */
+    public static function getAllGroupUidCount()
+    {
+        $group_uid_map = static::getAllGroupUidList();
+        $group_uid_count_map = array();
+        foreach ($group_uid_map as $group_id => $uid_list) {
+            $group_uid_count_map[$group_id] = count($uid_list);
+        }
+        return $group_uid_count_map;
+    }
+    /**
+     * 获取所有分组uid在线列表
+     *
+     * @return array
+     */
+    public static function getAllGroupUidList()
+    {
+        $data = static::select(array('uid','groups'));
+        $group_uid_map = array();
+        foreach ($data as $local_ip => $buffer_array) {
+            foreach ($buffer_array as $local_port => $items) {
+                //$items = ['connection_id'=>['uid'=>x, 'group'=>[x,x..], 'session'=>[..]], 'client_id'=>[..], ..];
+                foreach ($items as $connection_id => $info) {
+                    if (empty($info['uid']) || empty($info['groups'])) {
+                        break;
+                    }
+                    $uid = $info['uid'];
+                    foreach ($info['groups'] as $group_id) {
+                        if(!isset($group_uid_map[$group_id])) {
+                            $group_uid_map[$group_id] = array();
+                        }
+                        $group_uid_map[$group_id][$uid] = $uid;
+                    }
+                }
+            }
+        }
+        return $group_uid_map;
+    }
+    /**
+     * 获取所有群组在线client_id列表
+     *
+     * @return array
+     */
+    public static function getAllGroupClientIdList()
+    {
+        $data = static::select(array('groups'));
+        $group_client_id_map = array();
+        foreach ($data as $local_ip => $buffer_array) {
+            foreach ($buffer_array as $local_port => $items) {
+                //$items = ['connection_id'=>['uid'=>x, 'group'=>[x,x..], 'session'=>[..]], 'client_id'=>[..], ..];
+                foreach ($items as $connection_id => $info) {
+                    if (empty($info['groups'])) {
+                        break;
+                    }
+                    $client_id = Context::addressToClientId($local_ip, $local_port, $connection_id);
+                    foreach ($info['groups'] as $group_id) {
+                        if(!isset($group_client_id_map[$group_id])) {
+                            $group_client_id_map[$group_id] = array();
+                        }
+                        $group_client_id_map[$group_id][$client_id] = $client_id;
+                    }
+                }
+            }
+        }
+        return $group_client_id_map;
+    }
+    /**
+     * 获取所有群组在线client_id数量,也就是获取每个群组在线连接数
+     *
+     * @return array
+     */
+    public static function getAllGroupClientIdCount()
+    {
+        $group_client_map = static::getAllGroupClientIdList();
+        $group_client_count_map = array();
+        foreach ($group_client_map as $group_id => $client_id_list) {
+            $group_client_count_map[$group_id] = count($client_id_list);
+        }
+        return $group_client_count_map;
+    }
+    /**
+     * 根据条件到gateway搜索数据
+     *
+     * @param array $fields
+     * @param array $where
+     * @return array
+     */
+    protected static function select($fields = array('session','uid','groups'), $where = array())
+    {
+        $t = microtime(true);
+        $gateway_data             = GatewayProtocol::$empty;
+        $gateway_data['cmd']      = GatewayProtocol::CMD_SELECT;
+        $gateway_data['ext_data'] = array('fields' => $fields, 'where' => $where);
+        $gateway_data_list   = array();
+        // 有client_id,能计算出需要和哪些gateway通讯,只和必要的gateway通讯能降低系统负载
+        if (isset($where['client_id'])) {
+            $client_id_list = $where['client_id'];
+            unset($gateway_data['ext_data']['where']['client_id']);
+            $gateway_data['ext_data']['where']['connection_id'] = array();
+            foreach ($client_id_list as $client_id) {
+                $address_data = Context::clientIdToAddress($client_id);
+                if (!$address_data) {
+                    continue;
+                }
+                $address = long2ip($address_data['local_ip']) . ":{$address_data['local_port']}";
+                if (!isset($gateway_data_list[$address])) {
+                    $gateway_data_list[$address] = $gateway_data;
+                }
+                $gateway_data_list[$address]['ext_data']['where']['connection_id'][$address_data['connection_id']] = $address_data['connection_id'];
+            }
+            foreach ($gateway_data_list as $address => $item) {
+                $gateway_data_list[$address]['ext_data'] = json_encode($item['ext_data']);
+            }
+            // 有其它条件,则还是需要向所有gateway发送
+            if (count($where) !== 1) {
+                $gateway_data['ext_data'] = json_encode($gateway_data['ext_data']);
+                foreach (static::getAllGatewayAddress() as $address) {
+                    if (!isset($gateway_data_list[$address])) {
+                        $gateway_data_list[$address] = $gateway_data;
+                    }
+                }
+            }
+            $data = static::getBufferFromSomeGateway($gateway_data_list);
+        } else {
+            $gateway_data['ext_data'] = json_encode($gateway_data['ext_data']);
+            $data = static::getBufferFromAllGateway($gateway_data);
+        }
+        return $data;
+    }
+    /**
+     * 生成验证包,用于验证此客户端的合法性
+     * 
+     * @return string
+     */
+    protected static function generateAuthBuffer()
+    {
+        $gateway_data         = GatewayProtocol::$empty;
+        $gateway_data['cmd']  = GatewayProtocol::CMD_GATEWAY_CLIENT_CONNECT;
+        $gateway_data['body'] = json_encode(array(
+            'secret_key' => static::$secretKey,
+        ));
+        return GatewayProtocol::encode($gateway_data);
+    }
+    /**
+     * 批量向某些gateway发包,并得到返回数组
+     *
+     * @param array $gateway_data_array
+     * @return array
+     * @throws Exception
+     */
+    protected static function getBufferFromSomeGateway($gateway_data_array)
+    {
+        $gateway_buffer_array = array();
+        $auth_buffer = static::$secretKey ? static::generateAuthBuffer() : '';
+        foreach ($gateway_data_array as $address => $gateway_data) {
+            if ($auth_buffer) {
+                $gateway_buffer_array[$address] = $auth_buffer.GatewayProtocol::encode($gateway_data);
+            } else {
+                $gateway_buffer_array[$address] = GatewayProtocol::encode($gateway_data);
+            }
+        }
+        return static::getBufferFromGateway($gateway_buffer_array);
+    }
+    /**
+     * 批量向所有 gateway 发包,并得到返回数组
+     *
+     * @param string $gateway_data
+     * @return array
+     * @throws Exception
+     */
+    protected static function getBufferFromAllGateway($gateway_data)
+    {
+        $addresses = static::getAllGatewayAddress();
+        $gateway_buffer_array = array();
+        $gateway_buffer = GatewayProtocol::encode($gateway_data);
+        $gateway_buffer = static::$secretKey ? static::generateAuthBuffer() . $gateway_buffer : $gateway_buffer;
+        foreach ($addresses as $address) {
+            $gateway_buffer_array[$address] = $gateway_buffer;
+        }
+        return static::getBufferFromGateway($gateway_buffer_array);
+    }
+    /**
+     * 获取所有gateway内部通讯地址
+     *
+     * @return array
+     * @throws Exception
+     */
+    protected static function getAllGatewayAddress()
+    {
+        if (isset(static::$businessWorker)) {
+            $addresses = static::$businessWorker->getAllGatewayAddresses();
+            if (empty($addresses)) {
+                throw new Exception('businessWorker::getAllGatewayAddresses return empty');
+            }
+        } else {
+            $addresses = static::getAllGatewayAddressesFromRegister();
+            if (empty($addresses)) {
+                return array();
+            }
+        }
+        return $addresses;
+    }
+    /**
+     * 批量向gateway发送并获取数据
+     * @param $gateway_buffer_array
+     * @return array
+     */
+    protected static function getBufferFromGateway($gateway_buffer_array)
+    {
+        $client_array = $status_data = $client_address_map = $receive_buffer_array = $recv_length_array = array();
+        // 批量向所有gateway进程发送请求数据
+        foreach ($gateway_buffer_array as $address => $gateway_buffer) {
+            $client = stream_socket_client("tcp://$address", $errno, $errmsg, static::$connectTimeout);
+            if ($client && strlen($gateway_buffer) === stream_socket_sendto($client, $gateway_buffer)) {
+                $socket_id                        = (int)$client;
+                $client_array[$socket_id]         = $client;
+                $client_address_map[$socket_id]   = explode(':', $address);
+                $receive_buffer_array[$socket_id] = '';
+            }
+        }
+        // 超时5秒
+        $timeout    = 5;
+        $time_start = microtime(true);
+        // 批量接收请求
+        while (count($client_array) > 0) {
+            $write = $except = array();
+            $read  = $client_array;
+            if (@stream_select($read, $write, $except, $timeout)) {
+                foreach ($read as $client) {
+                    $socket_id = (int)$client;
+                    $buffer    = stream_socket_recvfrom($client, 65535);
+                    if ($buffer !== '' && $buffer !== false) {
+                        $receive_buffer_array[$socket_id] .= $buffer;
+                        $receive_length = strlen($receive_buffer_array[$socket_id]);
+                        if (empty($recv_length_array[$socket_id]) && $receive_length >= 4) {
+                            $recv_length_array[$socket_id] = current(unpack('N', $receive_buffer_array[$socket_id]));
+                        }
+                        if (!empty($recv_length_array[$socket_id]) && $receive_length >= $recv_length_array[$socket_id] + 4) {
+                            unset($client_array[$socket_id]);
+                        }
+                    } elseif (feof($client)) {
+                        unset($client_array[$socket_id]);
+                    }
+                }
+            }
+            if (microtime(true) - $time_start > $timeout) {
+                break;
+            }
+        }
+        $format_buffer_array = array();
+        foreach ($receive_buffer_array as $socket_id => $buffer) {
+            $local_ip                                    = ip2long($client_address_map[$socket_id][0]);
+            $local_port                                  = $client_address_map[$socket_id][1];
+            $format_buffer_array[$local_ip][$local_port] = unserialize(substr($buffer, 4));
+        }
+        return $format_buffer_array;
+    }
+    /**
+     * 踢掉某个客户端,并以$message通知被踢掉客户端
+     *
+     * @param int $client_id
+     * @param string $message
+     * @return void
+     */
+    public static function closeClient($client_id, $message = null)
+    {
+        if ($client_id === Context::$client_id) {
+            return static::closeCurrentClient($message);
+        } // 不是发给当前用户则使用存储中的地址
+        else {
+            $address_data = Context::clientIdToAddress($client_id);
+            if (!$address_data) {
+                return false;
+            }
+            $address      = long2ip($address_data['local_ip']) . ":{$address_data['local_port']}";
+            return static::kickAddress($address, $address_data['connection_id'], $message);
+        }
+    }
+    /**
+     * 踢掉某个客户端并直接立即销毁相关连接
+     *
+     * @param int $client_id
+     * @return bool
+     */
+    public static function destoryClient($client_id)
+    {
+        if ($client_id === Context::$client_id) {
+            return static::destoryCurrentClient();
+        } // 不是发给当前用户则使用存储中的地址
+        else {
+            $address_data = Context::clientIdToAddress($client_id);
+            if (!$address_data) {
+                return false;
+            }
+            $address = long2ip($address_data['local_ip']) . ":{$address_data['local_port']}";
+            return static::destroyAddress($address, $address_data['connection_id']);
+        }
+    }
+    /**
+     * 踢掉当前客户端并直接立即销毁相关连接
+     *
+     * @return bool
+     * @throws Exception
+     */
+    public static function destoryCurrentClient()
+    {
+        if (!Context::$connection_id) {
+            throw new Exception('destoryCurrentClient can not be called in async context');
+        }
+        $address = long2ip(Context::$local_ip) . ':' . Context::$local_port;
+        return static::destroyAddress($address, Context::$connection_id);
+    }
+    /**
+     * 将 client_id 与 uid 绑定
+     *
+     * @param int        $client_id
+     * @param int|string $uid
+     * @return void
+     */
+    public static function bindUid($client_id, $uid)
+    {
+        static::sendCmdAndMessageToClient($client_id, GatewayProtocol::CMD_BIND_UID, '', $uid);
+    }
+    /**
+     * 将 client_id 与 uid 解除绑定
+     *
+     * @param int        $client_id
+     * @param int|string $uid
+     * @return void
+     */
+    public static function unbindUid($client_id, $uid)
+    {
+        static::sendCmdAndMessageToClient($client_id, GatewayProtocol::CMD_UNBIND_UID, '', $uid);
+    }
+    /**
+     * 将 client_id 加入组
+     *
+     * @param int        $client_id
+     * @param int|string $group
+     * @return void
+     */
+    public static function joinGroup($client_id, $group)
+    {
+        static::sendCmdAndMessageToClient($client_id, GatewayProtocol::CMD_JOIN_GROUP, '', $group);
+    }
+    /**
+     * 将 client_id 离开组
+     *
+     * @param int        $client_id
+     * @param int|string $group
+     *
+     * @return void
+     */
+    public static function leaveGroup($client_id, $group)
+    {
+        static::sendCmdAndMessageToClient($client_id, GatewayProtocol::CMD_LEAVE_GROUP, '', $group);
+    }
+    /**
+     * 取消分组
+     *
+     * @param int|string $group
+     *
+     * @return void
+     */
+    public static function ungroup($group)
+    {
+        if (!static::isValidGroupId($group)) {
+            return false;
+        }
+        $gateway_data             = GatewayProtocol::$empty;
+        $gateway_data['cmd']      = GatewayProtocol::CMD_UNGROUP;
+        $gateway_data['ext_data'] = $group;
+        return static::sendToAllGateway($gateway_data);
+    }
+    /**
+     * 向所有 uid 发送
+     *
+     * @param int|string|array $uid
+     * @param string           $message
+     *
+     * @return void
+     */
+    public static function sendToUid($uid, $message)
+    {
+        $gateway_data         = GatewayProtocol::$empty;
+        $gateway_data['cmd']  = GatewayProtocol::CMD_SEND_TO_UID;
+        $gateway_data['body'] = $message;
+        if (!is_array($uid)) {
+            $uid = array($uid);
+        }
+        $gateway_data['ext_data'] = json_encode($uid);
+        static::sendToAllGateway($gateway_data);
+    }
+    /**
+     * 向 group 发送
+     *
+     * @param int|string|array $group             组(不允许是 0 '0' false null array()等为空的值)
+     * @param string           $message           消息
+     * @param array            $exclude_client_id 不给这些client_id发
+     * @param bool             $raw               发送原始数据(即不调用gateway的协议的encode方法)
+     *
+     * @return void
+     */
+    public static function sendToGroup($group, $message, $exclude_client_id = null, $raw = false)
+    {
+        if (!static::isValidGroupId($group)) {
+            return false;
+        }
+        $gateway_data         = GatewayProtocol::$empty;
+        $gateway_data['cmd']  = GatewayProtocol::CMD_SEND_TO_GROUP;
+        $gateway_data['body'] = $message;
+        if ($raw) {
+            $gateway_data['flag'] |= GatewayProtocol::FLAG_NOT_CALL_ENCODE;
+        }
+        if (!is_array($group)) {
+            $group = array($group);
+        }
+        // 分组发送,没有排除的client_id,直接发送
+        $default_ext_data_buffer = json_encode(array('group'=> $group, 'exclude'=> null));
+        if (empty($exclude_client_id)) {
+            $gateway_data['ext_data'] = $default_ext_data_buffer;
+            return static::sendToAllGateway($gateway_data);
+        }
+        // 分组发送,有排除的client_id,需要将client_id转换成对应gateway进程内的connectionId
+        if (!is_array($exclude_client_id)) {
+            $exclude_client_id = array($exclude_client_id);
+        }
+        $address_connection_array = static::clientIdArrayToAddressArray($exclude_client_id);
+        // 如果有businessWorker实例,说明运行在workerman环境中,通过businessWorker中的长连接发送数据
+        if (static::$businessWorker) {
+            foreach (static::$businessWorker->gatewayConnections as $address => $gateway_connection) {
+                $gateway_data['ext_data'] = isset($address_connection_array[$address]) ?
+                    json_encode(array('group'=> $group, 'exclude'=> $address_connection_array[$address])) :
+                    $default_ext_data_buffer;
+                /** @var TcpConnection $gateway_connection */
+                $gateway_connection->send($gateway_data);
+            }
+        } // 运行在其它环境中,通过注册中心得到gateway地址
+        else {
+            $addresses = static::getAllGatewayAddressesFromRegister();
+            foreach ($addresses as $address) {
+                $gateway_data['ext_data'] = isset($address_connection_array[$address]) ?
+                    json_encode(array('group'=> $group, 'exclude'=> $address_connection_array[$address])) :
+                    $default_ext_data_buffer;
+                static::sendToGateway($address, $gateway_data);
+            }
+        }
+    }
+    /**
+     * 更新 session,框架自动调用,开发者不要调用
+     *
+     * @param int    $client_id
+     * @param string $session_str
+     * @return bool
+     */
+    public static function setSocketSession($client_id, $session_str)
+    {
+        return static::sendCmdAndMessageToClient($client_id, GatewayProtocol::CMD_SET_SESSION, '', $session_str);
+    }
+    /**
+     * 设置 session,原session值会被覆盖
+     *
+     * @param int   $client_id
+     * @param array $session
+     *
+     * @return void
+     */
+    public static function setSession($client_id, array $session)
+    {
+        if (Context::$client_id === $client_id) {
+            $_SESSION = $session;
+            Context::$old_session = $_SESSION;
+        }
+        static::setSocketSession($client_id, Context::sessionEncode($session));
+    }
+    
+    /**
+     * 更新 session,实际上是与老的session合并
+     *
+     * @param int   $client_id
+     * @param array $session
+     *
+     * @return void
+     */
+    public static function updateSession($client_id, array $session)
+    {
+        if (Context::$client_id === $client_id) {
+            $_SESSION = array_replace_recursive((array)$_SESSION, $session);
+            Context::$old_session = $_SESSION;
+        }
+        static::sendCmdAndMessageToClient($client_id, GatewayProtocol::CMD_UPDATE_SESSION, '', Context::sessionEncode($session));
+    }
+    
+    /**
+     * 获取某个client_id的session
+     *
+     * @param int   $client_id
+     * @return mixed false表示出错、null表示用户不存在、array表示具体的session信息 
+     */
+    public static function getSession($client_id)
+    {
+        $address_data = Context::clientIdToAddress($client_id);
+        if (!$address_data) {
+            return false;
+        }
+        $address      = long2ip($address_data['local_ip']) . ":{$address_data['local_port']}";
+        if (isset(static::$businessWorker)) {
+            if (!isset(static::$businessWorker->gatewayConnections[$address])) {
+                return null;
+            }
+        }
+        $gateway_data                  = GatewayProtocol::$empty;
+        $gateway_data['cmd']           = GatewayProtocol::CMD_GET_SESSION_BY_CLIENT_ID;
+        $gateway_data['connection_id'] = $address_data['connection_id'];
+        return static::sendAndRecv($address, $gateway_data);
+    }
+    /**
+     * 向某个用户网关发送命令和消息
+     *
+     * @param int    $client_id
+     * @param int    $cmd
+     * @param string $message
+     * @param string $ext_data
+     * @return boolean
+     */
+    protected static function sendCmdAndMessageToClient($client_id, $cmd, $message, $ext_data = '')
+    {
+        // 如果是发给当前用户则直接获取上下文中的地址
+        if ($client_id === Context::$client_id || $client_id === null) {
+            $address       = long2ip(Context::$local_ip) . ':' . Context::$local_port;
+            $connection_id = Context::$connection_id;
+        } else {
+            $address_data  = Context::clientIdToAddress($client_id);
+            if (!$address_data) {
+                return false;
+            }
+            $address       = long2ip($address_data['local_ip']) . ":{$address_data['local_port']}";
+            $connection_id = $address_data['connection_id'];
+        }
+        $gateway_data                  = GatewayProtocol::$empty;
+        $gateway_data['cmd']           = $cmd;
+        $gateway_data['connection_id'] = $connection_id;
+        $gateway_data['body']          = $message;
+        if (!empty($ext_data)) {
+            $gateway_data['ext_data'] = $ext_data;
+        }
+        return static::sendToGateway($address, $gateway_data);
+    }
+    /**
+     * 发送数据并返回
+     *
+     * @param int   $address
+     * @param mixed $data
+     * @return bool
+     * @throws Exception
+     */
+    protected static function sendAndRecv($address, $data)
+    {
+        $buffer = GatewayProtocol::encode($data);
+        $buffer = static::$secretKey ? static::generateAuthBuffer() . $buffer : $buffer;
+        $client = stream_socket_client("tcp://$address", $errno, $errmsg, static::$connectTimeout);
+        if (!$client) {
+            throw new Exception("can not connect to tcp://$address $errmsg");
+        }
+        if (strlen($buffer) === stream_socket_sendto($client, $buffer)) {
+            $timeout = 5;
+            // 阻塞读
+            stream_set_blocking($client, 1);
+            // 1秒超时
+            stream_set_timeout($client, 1);
+            $all_buffer = '';
+            $time_start = microtime(true);
+            $pack_len = 0;
+            while (1) {
+                $buf = stream_socket_recvfrom($client, 655350);
+                if ($buf !== '' && $buf !== false) {
+                    $all_buffer .= $buf;
+                } else {
+                    if (feof($client)) {
+                        throw new Exception("connection close tcp://$address");
+                    } elseif (microtime(true) - $time_start > $timeout) {
+                        break;
+                    }
+                    continue;
+                }
+                $recv_len = strlen($all_buffer);
+                if (!$pack_len && $recv_len >= 4) {
+                    $pack_len= current(unpack('N', $all_buffer));
+                }
+                // 回复的数据都是以\n结尾
+                if (($pack_len && $recv_len >= $pack_len + 4) || microtime(true) - $time_start > $timeout) {
+                    break;
+                }
+            }
+            // 返回结果
+            return unserialize(substr($all_buffer, 4));
+        } else {
+            throw new Exception("sendAndRecv($address, \$bufer) fail ! Can not send data!", 502);
+        }
+    }
+    /**
+     * 发送数据到网关
+     *
+     * @param string $address
+     * @param array  $gateway_data
+     * @return bool
+     */
+    protected static function sendToGateway($address, $gateway_data)
+    {
+        return static::sendBufferToGateway($address, GatewayProtocol::encode($gateway_data));
+    }
+    /**
+     * 发送buffer数据到网关
+     * @param string $address
+     * @param string $gateway_buffer
+     * @return bool
+     */
+    protected static function sendBufferToGateway($address, $gateway_buffer)
+    {
+        // 有$businessWorker说明是workerman环境,使用$businessWorker发送数据
+        if (static::$businessWorker) {
+            if (!isset(static::$businessWorker->gatewayConnections[$address])) {
+                return false;
+            }
+            return static::$businessWorker->gatewayConnections[$address]->send($gateway_buffer, true);
+        }
+        // 非workerman环境
+        $gateway_buffer = static::$secretKey ? static::generateAuthBuffer() . $gateway_buffer : $gateway_buffer;
+        $flag           = static::$persistentConnection ? STREAM_CLIENT_PERSISTENT | STREAM_CLIENT_CONNECT : STREAM_CLIENT_CONNECT;
+        $client         = stream_socket_client("tcp://$address", $errno, $errmsg, static::$connectTimeout, $flag);
+        return strlen($gateway_buffer) == stream_socket_sendto($client, $gateway_buffer);
+    }
+    /**
+     * 向所有 gateway 发送数据
+     *
+     * @param string $gateway_data
+     * @throws Exception
+     *
+     * @return void
+     */
+    protected static function sendToAllGateway($gateway_data)
+    {
+        $buffer = GatewayProtocol::encode($gateway_data);
+        // 如果有businessWorker实例,说明运行在workerman环境中,通过businessWorker中的长连接发送数据
+        if (static::$businessWorker) {
+            foreach (static::$businessWorker->gatewayConnections as $gateway_connection) {
+                /** @var TcpConnection $gateway_connection */
+                $gateway_connection->send($buffer, true);
+            }
+        } // 运行在其它环境中,通过注册中心得到gateway地址
+        else {
+            $all_addresses = static::getAllGatewayAddressesFromRegister();
+            foreach ($all_addresses as $address) {
+                static::sendBufferToGateway($address, $buffer);
+            }
+        }
+    }
+    /**
+     * 踢掉某个网关的 socket
+     *
+     * @param string $address
+     * @param int    $connection_id
+     * @return bool
+     */
+    protected static function kickAddress($address, $connection_id, $message)
+    {
+        $gateway_data                  = GatewayProtocol::$empty;
+        $gateway_data['cmd']           = GatewayProtocol::CMD_KICK;
+        $gateway_data['connection_id'] = $connection_id;
+        $gateway_data['body'] = $message;
+        return static::sendToGateway($address, $gateway_data);
+    }
+    /**
+     * 销毁某个网关的 socket
+     *
+     * @param string $address
+     * @param int    $connection_id
+     * @return bool
+     */
+    protected static function destroyAddress($address, $connection_id)
+    {
+        $gateway_data                  = GatewayProtocol::$empty;
+        $gateway_data['cmd']           = GatewayProtocol::CMD_DESTROY;
+        $gateway_data['connection_id'] = $connection_id;
+        return static::sendToGateway($address, $gateway_data);
+    }
+    /**
+     * 将clientid数组转换成address数组
+     *
+     * @param array $client_id_array
+     * @return array
+     */
+    protected static function clientIdArrayToAddressArray(array $client_id_array)
+    {
+        $address_connection_array = array();
+        foreach ($client_id_array as $client_id) {
+            $address_data = Context::clientIdToAddress($client_id);
+            if ($address_data) {
+                $address                                                            = long2ip($address_data['local_ip']) .
+                    ":{$address_data['local_port']}";
+                $address_connection_array[$address][$address_data['connection_id']] = $address_data['connection_id'];
+            }
+        }
+        return $address_connection_array;
+    }
+    /**
+     * 设置 gateway 实例
+     *
+     * @param \GatewayWorker\BusinessWorker $business_worker_instance
+     */
+    public static function setBusinessWorker($business_worker_instance)
+    {
+        static::$businessWorker = $business_worker_instance;
+    }
+    /**
+     * 获取通过注册中心获取所有 gateway 通讯地址
+     *
+     * @return array
+     * @throws Exception
+     */
+    protected static function getAllGatewayAddressesFromRegister()
+    {
+        static $addresses_cache, $last_update;
+        $time_now = time();
+        $expiration_time = 1;
+        $register_addresses = (array)static::$registerAddress;
+        $client = null;
+        if(empty($addresses_cache) || $time_now - $last_update > $expiration_time) {
+            foreach ($register_addresses as $register_address) {
+                set_error_handler(function(){});
+                $client = stream_socket_client('tcp://' . $register_address, $errno, $errmsg, static::$connectTimeout);
+                restore_error_handler();
+                if ($client) {
+                    break;
+                }
+            }
+            if (!$client) {
+                throw new Exception('Can not connect to tcp://' . $register_address . ' ' . $errmsg);
+            }
+            fwrite($client, '{"event":"worker_connect","secret_key":"' . static::$secretKey . '"}' . "\n");
+            stream_set_timeout($client, 5);
+            $ret = fgets($client, 655350);
+            if (!$ret || !$data = json_decode(trim($ret), true)) {
+                throw new Exception('getAllGatewayAddressesFromRegister fail. tcp://' .
+                    $register_address . ' return ' . var_export($ret, true));
+            }
+            $last_update = $time_now;
+            $addresses_cache = $data['addresses'];
+        }
+        if (!$addresses_cache) {
+            throw new Exception('Gateway::getAllGatewayAddressesFromRegister() with registerAddress:' .
+                json_encode(static::$registerAddress) . '  return ' . var_export($addresses_cache, true));
+        }
+        return $addresses_cache;
+    }
+    /**
+     * 检查群组id是否合法
+     *
+     * @param $group
+     * @return bool
+     */
+    protected static function isValidGroupId($group)
+    {
+        if (empty($group)) {
+            echo new \Exception('group('.var_export($group, true).') empty');
+            return false;
+        }
+        return true;
+    }
+}
+/**
+ * 上下文 包含当前用户uid, 内部通信local_ip local_port socket_id ,以及客户端client_ip client_port
+ */
+class Context
+{
+    /**
+     * 内部通讯id
+     * @var string
+     */
+    public static $local_ip;
+    /**
+     * 内部通讯端口
+     * @var int
+     */
+    public static $local_port;
+    /**
+     * 客户端ip
+     * @var string
+     */
+    public static $client_ip;
+    /**
+     * 客户端端口
+     * @var int
+     */
+    public static $client_port;
+    /**
+     * client_id
+     * @var string
+     */
+    public static $client_id;
+    /**
+     * 连接connection->id
+     * @var int
+     */
+    public static $connection_id;
+    /**
+     * 旧的session
+     *
+     * @var string
+     */
+    public static $old_session;
+    /**
+     * 编码session
+     * @param mixed $session_data
+     * @return string
+     */
+    public static function sessionEncode($session_data = '')
+    {
+        if($session_data !== '')
+        {
+            return serialize($session_data);
+        }
+        return '';
+    }
+    /**
+     * 解码session
+     * @param string $session_buffer
+     * @return mixed
+     */
+    public static function sessionDecode($session_buffer)
+    {
+        return unserialize($session_buffer);
+    }
+    /**
+     * 清除上下文
+     * @return void
+     */
+    public static function clear()
+    {
+        static::$local_ip = static::$local_port = static::$client_ip = static::$client_port =
+        static::$client_id = static::$connection_id  = static::$old_session = null;
+    }
+    /**
+     * 通讯地址到client_id的转换
+     * @return string
+     */
+    public static function addressToClientId($local_ip, $local_port, $connection_id)
+    {
+        return bin2hex(pack('NnN', $local_ip, $local_port, $connection_id));
+    }
+    /**
+     * client_id到通讯地址的转换
+     * @return array
+     */
+    public static function clientIdToAddress($client_id)
+    {
+        if(strlen($client_id) !== 20)
+        {
+            throw new \Exception("client_id $client_id is invalid");
+        }
+        return unpack('Nlocal_ip/nlocal_port/Nconnection_id' ,pack('H*', $client_id));
+    }
+}
+/**
+ * Gateway 与 Worker 间通讯的二进制协议
+ *
+ * struct GatewayProtocol
+ * {
+ *     unsigned int        pack_len,
+ *     unsigned char       cmd,//命令字
+ *     unsigned int        local_ip,
+ *     unsigned short      local_port,
+ *     unsigned int        client_ip,
+ *     unsigned short      client_port,
+ *     unsigned int        connection_id,
+ *     unsigned char       flag,
+ *     unsigned short      gateway_port,
+ *     unsigned int        ext_len,
+ *     char[ext_len]       ext_data,
+ *     char[pack_length-HEAD_LEN] body//包体
+ * }
+ * NCNnNnNCnN
+ */
+class GatewayProtocol
+{
+    // 发给worker,gateway有一个新的连接
+    const CMD_ON_CONNECT = 1;
+    // 发给worker的,客户端有消息
+    const CMD_ON_MESSAGE = 3;
+    // 发给worker上的关闭链接事件
+    const CMD_ON_CLOSE = 4;
+    // 发给gateway的向单个用户发送数据
+    const CMD_SEND_TO_ONE = 5;
+    // 发给gateway的向所有用户发送数据
+    const CMD_SEND_TO_ALL = 6;
+    // 发给gateway的踢出用户
+    // 1、如果有待发消息,将在发送完后立即销毁用户连接
+    // 2、如果无待发消息,将立即销毁用户连接
+    const CMD_KICK = 7;
+    // 发给gateway的立即销毁用户连接
+    const CMD_DESTROY = 8;
+    // 发给gateway,通知用户session更新
+    const CMD_UPDATE_SESSION = 9;
+    // 获取在线状态
+    const CMD_GET_ALL_CLIENT_SESSIONS = 10;
+    // 判断是否在线
+    const CMD_IS_ONLINE = 11;
+    // client_id绑定到uid
+    const CMD_BIND_UID = 12;
+    // 解绑
+    const CMD_UNBIND_UID = 13;
+    // 向uid发送数据
+    const CMD_SEND_TO_UID = 14;
+    // 根据uid获取绑定的clientid
+    const CMD_GET_CLIENT_ID_BY_UID = 15;
+    // 加入组
+    const CMD_JOIN_GROUP = 20;
+    // 离开组
+    const CMD_LEAVE_GROUP = 21;
+    // 向组成员发消息
+    const CMD_SEND_TO_GROUP = 22;
+    // 获取组成员
+    const CMD_GET_CLIENT_SESSIONS_BY_GROUP = 23;
+    // 获取组在线连接数
+    const CMD_GET_CLIENT_COUNT_BY_GROUP = 24;
+    // 按照条件查找
+    const CMD_SELECT = 25;
+    // 获取在线的群组ID
+    const CMD_GET_GROUP_ID_LIST = 26;
+    // 取消分组
+    const CMD_UNGROUP = 27;
+    // worker连接gateway事件
+    const CMD_WORKER_CONNECT = 200;
+    // 心跳
+    const CMD_PING = 201;
+    // GatewayClient连接gateway事件
+    const CMD_GATEWAY_CLIENT_CONNECT = 202;
+    // 根据client_id获取session
+    const CMD_GET_SESSION_BY_CLIENT_ID = 203;
+    // 发给gateway,覆盖session
+    const CMD_SET_SESSION = 204;
+    // 当websocket握手时触发,只有websocket协议支持此命令字
+    const CMD_ON_WEBSOCKET_CONNECT = 205;
+    // 包体是标量
+    const FLAG_BODY_IS_SCALAR = 0x01;
+    // 通知gateway在send时不调用协议encode方法,在广播组播时提升性能
+    const FLAG_NOT_CALL_ENCODE = 0x02;
+    /**
+     * 包头长度
+     *
+     * @var int
+     */
+    const HEAD_LEN = 28;
+    public static $empty = array(
+        'cmd'           => 0,
+        'local_ip'      => 0,
+        'local_port'    => 0,
+        'client_ip'     => 0,
+        'client_port'   => 0,
+        'connection_id' => 0,
+        'flag'          => 0,
+        'gateway_port'  => 0,
+        'ext_data'      => '',
+        'body'          => '',
+    );
+    /**
+     * 返回包长度
+     *
+     * @param string $buffer
+     * @return int return current package length
+     */
+    public static function input($buffer)
+    {
+        if (strlen($buffer) < self::HEAD_LEN) {
+            return 0;
+        }
+        $data = unpack("Npack_len", $buffer);
+        return $data['pack_len'];
+    }
+    /**
+     * 获取整个包的 buffer
+     *
+     * @param mixed $data
+     * @return string
+     */
+    public static function encode($data)
+    {
+        $flag = (int)is_scalar($data['body']);
+        if (!$flag) {
+            $data['body'] = serialize($data['body']);
+        }
+        $data['flag'] |= $flag;
+        $ext_len      = strlen($data['ext_data']);
+        $package_len  = self::HEAD_LEN + $ext_len + strlen($data['body']);
+        return pack("NCNnNnNCnN", $package_len,
+                $data['cmd'], $data['local_ip'],
+                $data['local_port'], $data['client_ip'],
+                $data['client_port'], $data['connection_id'],
+                $data['flag'], $data['gateway_port'],
+                $ext_len) . $data['ext_data'] . $data['body'];
+    }
+    /**
+     * 从二进制数据转换为数组
+     *
+     * @param string $buffer
+     * @return array
+     */
+    public static function decode($buffer)
+    {
+        $data = unpack("Npack_len/Ccmd/Nlocal_ip/nlocal_port/Nclient_ip/nclient_port/Nconnection_id/Cflag/ngateway_port/Next_len",
+            $buffer);
+        if ($data['ext_len'] > 0) {
+            $data['ext_data'] = substr($buffer, self::HEAD_LEN, $data['ext_len']);
+            if ($data['flag'] & self::FLAG_BODY_IS_SCALAR) {
+                $data['body'] = substr($buffer, self::HEAD_LEN + $data['ext_len']);
+            } else {
+                $data['body'] = unserialize(substr($buffer, self::HEAD_LEN + $data['ext_len']));
+            }
+        } else {
+            $data['ext_data'] = '';
+            if ($data['flag'] & self::FLAG_BODY_IS_SCALAR) {
+                $data['body'] = substr($buffer, self::HEAD_LEN);
+            } else {
+                $data['body'] = unserialize(substr($buffer, self::HEAD_LEN));
+            }
+        }
+        return $data;
+    }
+}

+ 306 - 147
public/static/libs/amazeui/js/wechat.js

@@ -146,6 +146,7 @@ function add_click_user(){
 
 	$(".pc_msg_user_list li").off('click');
 	$(".pc_msg_user_list li").click(function(){
+		$(this).find(".shownum").removeClass("ck");
 		$(".pc_msg_user_list li").removeClass('user_active');
 		$(this).addClass('user_active');
 		uid = $(this).data('uid');
@@ -244,6 +245,148 @@ function format_chat_msg(array){
 		return str;
 }
 
+
+	//刷新最近的消息用户
+	function check_list_new_msgnum(){
+		$.get(ListMsgUserUrl+"1",function(res){
+			if(res.code==0){
+				var remind = true;
+				$.each(res.ext.s_data,function(i,rs){
+					//出现新的消息新用户,或者是原来新消息的用户又发来了新消息
+					if(typeof(uid_array[rs.f_uid])=='undefined'||rs.id>uid_array[rs.f_uid]){
+						console.log('有新的消息来了');
+						$('.pc_msg_user_list').html(res.data);
+						add_click_user();
+						if(remind && window.Notification){	//消息提醒
+							remind = false;
+							if(Notification.permission=="granted"){
+								pushNotice();
+							}else{
+								Notification.requestPermission(function(status) {                  
+									if (status === "granted") {
+										pushNotice();
+									}
+								});
+							}
+						}
+					}
+					//新消息已读
+					if(rs.new_num<1){
+						$('.pc_msg_user_list .list_'+rs.f_uid+' .shownum').removeClass('ck');
+						$('.pc_msg_user_list .list_'+rs.f_uid+' .shownum').html(rs.num>999?'99+':rs.num);
+					}
+					//console.log(rs.f_uid+'='+rs.id+'='+uid_array[rs.f_uid]);
+					uid_array[rs.f_uid] = rs.id;
+				});
+			}
+		});
+	}
+
+	//右下角弹信息提示,有新消息来了
+	function pushNotice(){
+		var m = new Notification('新消息提醒', {body: '你收到一条新消息,请注意查收',});
+			m.onclick = function () { window.focus();}
+	}
+
+//优先显示底部的内容
+	function goto_bottom(vh){
+		var iCount = setInterval(function() {
+			var obj = $(".pc_show_all_msg");
+			var h = obj.height();
+			//console.log( '实际的高度='+h);
+			if(h>vh){
+				clearInterval(iCount);
+				show_msg_top = h-453;
+				obj.css({top:(-show_msg_top)+"px"});
+				console.log('top='+show_msg_top)
+			}
+		}, 200);
+	}
+
+//建立WebSocket长连接
+var clientId;
+function ws_connect(){
+	if(ws!=null&&ws_stop!=true){
+		$.get("/index.php/index/wxapp.msg/bind_group.html?uid="+uid+"&client_id="+clientId,function(res){	//绑定用户
+					if(res.code==0){
+						layer.msg('欢迎到来!',{time:500});
+					}else{
+						layer.alert(res.msg);
+					}
+		});
+		return ;
+	}
+		ws = new WebSocket(ws_url);
+		ws.onmessage = function(e){
+			var obj = {};
+			try {
+				obj = JSON.parse(e.data);
+			}catch(err){
+				console.log(err);
+			}
+			if(obj.type=='newmsg'){
+				//check_new_showmsg(obj);	//非圈子成员的话,就适合推送
+				check_new_showmsg();	//圈子成员或私聊的话,就适合拉数据,因为要同时更新是否已读标志
+				console.log("聊天窗口,有新消息来了!!!!!!!!!!");
+				console.log(obj);
+			}else if(obj.type=='connect'){	//建立链接时得到客户的ID
+				clientId = obj.client_id;
+				$.get("/index.php/index/wxapp.msg/bind_group.html?uid="+uid+"&client_id="+clientId,function(res){	//绑定用户
+					if(res.code==0){
+						layer.msg('欢迎到来!',{time:500});
+					}else{
+						layer.alert(res.msg);
+					}
+				});
+			}else if(obj.type=='msglist'){	//需要更新列表信息
+				console.log("消息列表,有新消息来了..........");
+				console.log(e.data);
+				//alert("需要更新列表信息");
+				//obj.uid==uid即本圈子提交数据(或者自己正处于跟他人私聊),不用更新列表, obj.uid它人私信自己,就要更新,obj.uid是其它圈子也要更新
+				if( (obj.uid<0 && obj.uid!=uid) || (obj.uid==my_uid && obj.from_uid!=uid ) ){
+					check_list_new_msgnum();
+				}
+			}else{
+				console.log(e.data);
+			}
+		};
+
+		ws.error = function(e){
+			ws_stop = true;
+		};
+		ws.close = function(e){
+			ws_stop = true;
+		};
+		
+		if(typeof(chat_timer)!='undefined')clearInterval(chat_timer);
+		chat_timer = setInterval(function() {
+			ws.send('{"type":"refresh"}');
+		}, 1000*50);	//50秒发送一次心跳
+}
+
+//初次加载成功
+function load_first_page(res){
+	maxid = res.ext.maxid;
+
+	ws_url = res.ext.ws_url;
+
+	if(ws_url==''){	//没有设置WS的话,就用AJAX轮询
+		check_new = setInterval(function(){
+			if(maxid>=0)check_new_showmsg();
+		},9000);	//没有发信息之前刷新时间不宜太快,9秒刷新一次
+
+		setInterval(function() {
+			//list_i++;
+			//if(list_i%list_time==0)
+			check_list_new_msgnum();	//每隔20秒获取一次列表数据
+		}, 1000*20);
+	}else{
+		ws_connect();	//建立长链接
+	}
+
+	set_live_player(res);	//检查是否有视频直播
+}
+
 //加载更多的会话记录
 function showMoreMsg(uid){
 	if(show_msg_page==1){
@@ -257,8 +400,7 @@ function showMoreMsg(uid){
 		//console.log(res.data);
 		if(res.code==0){
 			if(show_msg_page==1){
-				maxid = res.ext.maxid;
-				set_live_player(res);	//检查是否有视频直播
+				load_first_page(res);				
 			}
 			set_main_win_content(res);
 		}else{
@@ -267,6 +409,96 @@ function showMoreMsg(uid){
 	});
 }
 
+//刷新会话用户中有没有新消息
+var num = ck_num = 0;
+function check_new_showmsg(obj){
+    if(ws_url==''){	//没有设置WS的话,就用AJAX轮询
+        if(ck_num>num){
+            console.log("服务器还没反馈数据过来");
+            //layer.msg("服务器反馈超时",{time:500});
+            return ;
+        }
+    }
+    
+    if( typeof(obj)=='object' && typeof(obj.data)=='object' && obj.data.length>0 ){		//服务端推数据, 即被动获取数据
+        var res = obj;
+        
+        var that = $('.pc_show_all_msg');
+        res.data = format_chat_msg(res.data);
+        if(res.data!=""){	//有新的聊天内容
+            var vh = that.height();
+            //console.log( '原来的高度='+vh);
+            that.prepend(res.data);
+            format_show_time(that)	//隐藏相邻的时间
+            goto_bottom(vh);
+            add_btn_delmsg();
+            need_scroll = true;
+            if(window.Notification){	//消息提醒
+                if(Notification.permission=="granted"){
+                    pushNotice();
+                }else{
+                    Notification.requestPermission(function(status) {
+                        if (status === "granted") {
+                            pushNotice();
+                        }
+                    });
+                }
+            }
+        }
+        
+        add_msg_data(res,'new');
+        maxid = res.ext.maxid;	//不主动获取数据的话,这个用不到
+        set_live_player(res,'cknew');	//设置视频直播的播放器
+        
+    }else{	//客户端拉数据, 主动获取数据
+        
+        $.get(getShowMsgUrl+"1&maxid="+maxid+"&uid="+uid+"&num="+num,function(res){
+            if(res.code!=0){
+                layer.alert('页面加载失败,请刷新当前网页');
+                return ;
+            }
+            set_live_player(res,'cknew');	//检查是否有视频直播
+            num++;
+            ck_num = num;
+            var that = $('.pc_show_all_msg');
+            res.data = format_chat_msg(res.data);
+            if(res.data!=""){	//有新的聊天内容
+                var vh = that.height();
+                //console.log( '原来的高度='+vh);
+                that.prepend(res.data);
+                format_show_time(that)	//隐藏相邻的时间
+                goto_bottom(vh);
+                add_btn_delmsg();
+                need_scroll = true;
+                if(window.Notification){	//消息提醒
+                    if(Notification.permission=="granted"){
+                        pushNotice();
+                    }else{
+                        Notification.requestPermission(function(status) {
+                            if (status === "granted") {
+                                pushNotice();
+                            }
+                        });
+                    }
+                }
+            }
+            //console.log( '='+res.ext.lasttime);
+            maxid = res.ext.maxid;
+            if(res.ext.lasttime<3){	//3秒内对方还在当前页面的话,就提示当前用户不要关闭当前窗口
+                if(uid>0){
+                    $("#remind_online").html("对方正在输入中,请稍候...");
+                }else{
+                    $("#remind_online").html("有用户在线");
+                }
+                $("#remind_online").show();
+            }else{
+                $("#remind_online").hide();
+            }
+        });
+            ck_num++;
+    }
+}
+
 //往主窗口里边加入显示的数据
 function set_main_win_content(res){
 	layer.closeAll();
@@ -366,19 +598,52 @@ var need_scroll = false;
 var user_num = 0;		//圈内成员数
 var user_list = {};	//圈内成员列表
 var have_load_live_player=false;
-
+var check_new;
+var ws=null,ws_url,ws_stop = false;
+//var list_i=0,list_time=30;	//每隔30秒获取一次列表数据
 
 $(function(){
 	
-	var num = ck_num = 0;
 	var pc_show_all_msg_obj = $(".pc_show_all_msg");
 	var pc_msg_user_list_obj = $(".pc_msg_user_list");
-	var list_i=0,list_time=15;	//每隔15秒获取一次列表数据
+
+	$(document).on("mousewheel DOMMouseScroll", function (e) {
+			var delta = (e.originalEvent.wheelDelta && (e.originalEvent.wheelDelta > 0 ? 1 : -1)) ||  // chrome & ie
+					(e.originalEvent.detail && (e.originalEvent.detail > 0 ? -1 : 1));              // firefox
+			if (delta > 0) {
+				
+				//监听会话内容的滚动条
+				var msg_top = pc_show_all_msg_obj.css('top');		
+				msg_top = Math.abs(msg_top.replace('px',''));	
+				console.log("向上滚"+msg_top);
+				//console.log("高_"+$(".pc_show_all_msg").height()) 
+				if( msg_top<100 && msg_scroll==true){
+					if(show_msg_top>0||show_msg_page>1){
+						if(chat_type=='tongji'){
+							get_tongji_msg(tj_type);
+						}else{
+							showMoreMsg(uid);
+						}				
+					}			
+				}
+			} else if (delta < 0) {
+				 
+				//监听用户列表的滚动条
+				var user_top = pc_msg_user_list_obj.css('top');
+				user_top = Math.abs(user_top.replace('px',''));	
+				console.log("向下滚"+user_top);
+				if(user_top-user_div_top>300 && user_scroll==true){
+					//console.log(user_div_top);
+					user_div_top = user_top;		
+					showMore_User();
+				}
+			}
+	});
+	
 	setInterval(function() {
 
 		//监听会话内容的滚动条
-		var msg_top = pc_show_all_msg_obj.css('top');
-		
+		var msg_top = pc_show_all_msg_obj.css('top');		
 		msg_top = Math.abs(msg_top.replace('px',''));	
 		//console.log("高_"+$(".pc_show_all_msg").height()) 
 		if( msg_top<100 && msg_scroll==true){
@@ -404,18 +669,12 @@ $(function(){
 		//	if(user_scroll==true)showMore_User();	//定时把他们全加载出来,方便做搜索使用.其实上面的滚动可删除了
 		//}, 4000);
 
-		//if(maxid>=0)check_new_showmsg();
-		list_i++;
-		if(list_i%list_time==0)check_list_new_msgnum();	//每隔15秒获取一次列表数据		
+		//if(maxid>=0)check_new_showmsg();				
 
-	}, 1000);
-
-
-	var check_new = setInterval(function(){
-		if(maxid>=0)check_new_showmsg();
-	},9000);	//没有发信息之前刷新时间不宜太快,9秒刷新一次
+	}, 1000*10000);//永远不执行
 
 
+	
 	$(".friends_list li > p").click(function(){
 		if($(this).find('i').is('.fa-chevron-up')){
 			$(this).find('i').removeClass('fa-chevron-up');
@@ -428,118 +687,11 @@ $(function(){
 		}
 	});
 
-
-	//刷新最近的消息用户
-	function check_list_new_msgnum(){
-		$.get(ListMsgUserUrl+"1",function(res){
-			if(res.code==0){			
-				$.each(res.ext.s_data,function(i,rs){
-					//出现新的消息新用户,或者是原来新消息的用户又发来了新消息
-					if(typeof(uid_array[rs.f_uid])=='undefined'||rs.id>uid_array[rs.f_uid]){ console.log('有新的消息来了');
-						$('.pc_msg_user_list').html(res.data);
-						add_click_user();
-						if(num>10 && window.Notification){	//消息提醒
-							if(Notification.permission=="granted"){
-								pushNotice();
-							}else{
-								Notification.requestPermission(function(status) {                  
-									if (status === "granted") {
-										pushNotice();
-									}
-								});
-							}
-						}
-					}
-					//新消息已读
-					if(rs.new_num<1){
-						$('.pc_msg_user_list .list_'+rs.f_uid+' .shownum').removeClass('ck');
-						$('.pc_msg_user_list .list_'+rs.f_uid+' .shownum').html(rs.num>999?'99+':rs.num);
-					}
-					//console.log(rs.f_uid+'='+rs.id+'='+uid_array[rs.f_uid]);
-					uid_array[rs.f_uid] = rs.id;
-				});
-			}
-		});
-	}
-
-
-	//刷新会话用户中有没有新消息
-	function check_new_showmsg(){
-		if(ck_num>num){
-			console.log("服务器还没反馈数据过来");
-			//layer.msg("服务器反馈超时",{time:500});
-			return ;
-		}
-		$.get(getShowMsgUrl+"1&maxid="+maxid+"&uid="+uid+"&num="+num,function(res){
-			if(res.code!=0){
-				layer.alert('页面加载失败,请刷新当前网页');
-				return ;
-			}
-			set_live_player(res,'cknew');	//检查是否有视频直播
-			num++;
-			ck_num = num;
-			var that = $('.pc_show_all_msg');
-			res.data = format_chat_msg(res.data);
-			if(res.data!=""){	//有新的聊天内容
-				var vh = that.height();
-				//console.log( '原来的高度='+vh);
-				that.prepend(res.data);
-				format_show_time(that)	//隐藏相邻的时间
-				goto_bottom(vh);
-				add_btn_delmsg();
-				need_scroll = true;
-				if(window.Notification){	//消息提醒
-					if(Notification.permission=="granted"){
-						pushNotice();
-					}else{
-						Notification.requestPermission(function(status) {                  
-							if (status === "granted") {
-								pushNotice();
-							}
-						});
-					}
-				}			
-			}
-			//console.log( '='+res.ext.lasttime);
-			maxid = res.ext.maxid;
-			if(res.ext.lasttime<3){	//3秒内对方还在当前页面的话,就提示当前用户不要关闭当前窗口
-				if(uid>0){
-					$("#remind_online").html("对方正在输入中,请稍候...");
-				}else{
-					$("#remind_online").html("有用户在线");
-				}
-				$("#remind_online").show();
-			}else{
-				$("#remind_online").hide();
-			}			
-		});
-		ck_num++;
-	}
-
-	function pushNotice(){
-		var m = new Notification('新消息提醒', {body: '你收到一条新消息,请注意查收',});
-			m.onclick = function () { window.focus();}
-	}
-
-	//优先显示底部的内容
-	function goto_bottom(vh){
-		var iCount = setInterval(function() {
-			var obj = $(".pc_show_all_msg");
-			var h = obj.height();
-			//console.log( '实际的高度='+h);
-			if(h>vh){
-				clearInterval(iCount);
-				show_msg_top = h-453;
-				obj.css({top:(-show_msg_top)+"px"});
-				console.log('top='+show_msg_top)
-			}
-		}, 200);
-	}
 	goto_bottom(500)
 
 	//统计数据的类型选择
 	var tongji_num = 0;//parseInt($("#tongji_num").html());
-	$("#tongji li").each(function(){
+	$("#tongji li").each(function(i){
 		var that = $(this);
 		var type = that.data('type');
 		that.click(function(){
@@ -557,19 +709,20 @@ $(function(){
 			that.find('em').hide();
 			get_tongji_msg(type)
 		});
-		
-		//各种动态的新数据统计		
-		$.get(tongjiCountUrl+'?type='+type,function(res){
-			if(res.code==0 && res.data>0){
-				that.find('em').html(res.data>999?'99+':res.data);
-				that.find('em').addClass('ck');
-				tongji_num = tongji_num+res.data;
-				$("#tongji_num").html(tongji_num>999?'99+':tongji_num);
-				$("#tongji_num").css('display','block');
-			}else{
-				that.find('em').hide();
-			}
-		});
+		setTimeout(function(){
+			//各种动态的新数据统计		
+			$.get(tongjiCountUrl+'?type='+type,function(res){
+				if(res.code==0 && res.data>0){
+					that.find('em').html(res.data>999?'99+':res.data);
+					that.find('em').addClass('ck');
+					tongji_num = tongji_num+res.data;
+					$("#tongji_num").html(tongji_num>999?'99+':tongji_num);
+					$("#tongji_num").css('display','block');
+				}else{
+					that.find('em').hide();
+				}
+			});
+		},2000*i+2000);
 	})
 
 
@@ -631,18 +784,24 @@ $(function(){
 		allowsend = false;
 		$.post(postMsgUrl,{'uid':uid,'content':content,},function(res){
 
-			//发布信息后,代表存在互动,缩短刷新时间
-			list_time = 5;
-			clearInterval(check_new);
-			check_new = setInterval(function(){
-				//if(maxid>=0)
-				check_new_showmsg();
-			},1500);
+			if(ws_url==''){	//没有设置WS的话,就用AJAX轮询
+				//发布信息后,代表存在互动,缩短刷新时间
+				//list_time = 5;
+				clearInterval(check_new);
+				check_new = setInterval(function(){
+					//if(maxid>=0)
+					check_new_showmsg();
+				},1500);
+			}
+
+			if(ws_stop==true){	//如果中断了,就要重连
+				ws_connect();
+			}
 
 			allowsend = true;
 			if(res.code==0){				
-				layer.msg('发送成功');
-				$("#hack_wrap").hide(300);
+				//layer.msg('发送成功',{time:500});
+				$("#hack_wrap").hide(100);
 			}else{
 				$(".msgcontent").val(content);
 				layer.alert('发送失败:'+res.msg);
@@ -657,7 +816,7 @@ $(function(){
 	$("#input_box").unbind('keydown').bind('keydown', function(e){
 		console.log(e.ctrlKey +'  '+e.keyCode);
 		if(e.ctrlKey && e.keyCode==13){
-			layer.msg('正在发送消息');
+			//layer.msg('正在发送消息');
 			postmsg();
 		}
 	});

+ 149 - 80
public/static/libs/bui/pages/chat/chat.js

@@ -24,6 +24,100 @@ loader.define(function(require,exports,module) {
 	var uiSidebar;          // 侧边栏
 	var video_player;
 	var have_load_live_player=false;
+	var ws,ws_url,ws_stop = false;
+
+	//建立WebSocket长连接
+	pageview.ws_connect = function(){
+		ws = new WebSocket(ws_url);
+		ws.onmessage = function(e){
+			var obj = {};
+			try {
+				obj = JSON.parse(e.data);
+			}catch(err){
+				console.log(err);
+			}
+			if(obj.type=='newmsg'){
+				//check_new_showmsg(obj);	//非圈子成员的话,就适合推送
+				check_new_showmsg();	//圈子成员或私聊的话,就适合拉数据,因为要同时更新是否已读标志
+				console.log("有新消息来了");
+				console.log(obj);
+			}else if(obj.type=='connect'){	//建立链接时得到客户的ID
+				$.get("/index.php/index/wxapp.msg/bind_group.html?uid="+uid+"&client_id="+obj.client_id,function(res){	//绑定用户
+					if(res.code==0){
+						layer.msg('欢迎到来!',{time:500});
+					}else{
+						layer.alert(res.msg);
+					}
+				});
+			}else{
+				console.log(e.data);
+			}
+		};
+
+		ws.error = function(e){
+			ws_stop = true;
+		};
+		ws.close = function(e){
+			ws_stop = true;
+		};
+		
+		if(typeof(chat_timer)!='undefined')clearInterval(chat_timer);
+		chat_timer = setInterval(function() {
+			ws.send('{"type":"refresh"}');
+		}, 1000*50);	//50秒发送一次心跳
+	}
+
+	//加载到第一页成功后,就获得了相关数据,才好进行其它的操作
+	function load_first_page(res){
+		maxid = res.ext.maxid;
+
+		quninfo = res.ext.qun_info;	//圈子信息
+		window.store.set("quninfo",quninfo);
+		//vues.set_quninfo(quninfo);
+		router.$("#send_user_name").html(quninfo.title);
+
+		qun_userinfo = res.ext.qun_userinfo;	//当前圈子用户信息 不存的话,就是为空即==''
+		userinfo = res.ext.userinfo;	//当前用户登录信息
+		head_menu(uid,quninfo,qun_userinfo,userinfo);
+		
+		ws_url = res.ext.ws_url;
+		
+		if(ws_url==''){	//没有设置WS的话,就用AJAX轮询
+			if(typeof(chat_timer)!='undefined')clearInterval(chat_timer);
+			refresh_i=0;
+			refresh_timenum = 8;//初始化8秒刷新一次
+			chat_timer = setInterval(function() {
+				refresh_i++;
+				//刷新会话用户中有没有新消息,必须要加载到内容后有maxid值才去刷新 初始化还没互动之前,不要刷新太快
+				if(maxid>=0 && refresh_i%refresh_timenum==0)check_new_showmsg();	
+			}, 1000);
+		}else{
+			pageview.ws_connect();	//建立长链接
+		}
+
+		setTimeout(function(){
+			set_live_player(res);	//设置视频直播的播放器
+
+			if(have_load_live_player==true){	//直播的时候,就不弹出签到了,影响界面布局
+				$.get("/index.php/p/signin-api-get_cfg/id/"+quninfo.id+".html",function(res){
+					if(res.code==0){
+						if(res.data.today_have_signin==true){
+							console.log('今天已经签到过了');
+						}else{
+							router.loadPart({
+								id: "#hack_signin",
+								url: "/public/static/libs/bui/pages/signin/pop.html?fdd",
+							}).then(function (module) {
+								module.api(quninfo,qun_userinfo,userinfo,res.data);
+							});
+						}					
+					}
+				});			
+			}
+
+			pageview.weixin_share();
+		},1000);
+	}
 
     // 模块初始化定义
     pageview.init = function () {
@@ -80,16 +174,6 @@ loader.define(function(require,exports,module) {
 		}
 
 
-		//console.log(chat_timer);
-		if(typeof(chat_timer)!='undefined')clearInterval(chat_timer);
-		refresh_i=0;
-		refresh_timenum = 8;//初始化8秒刷新一次
-		chat_timer = setInterval(function() {
-			refresh_i++;
-			//刷新会话用户中有没有新消息,必须要加载到内容后有maxid值才去刷新 初始化还没互动之前,不要刷新太快
-			if(maxid>=0 && refresh_i%refresh_timenum==0)check_new_showmsg();	
-		}, 1000);	
-		
 		//this.upload();
 		//loader.import(["/public/static/js/exif.js"],function(){});	//上传图片要获取图片信息
 
@@ -260,39 +344,51 @@ loader.define(function(require,exports,module) {
 
 	var num = ck_num = 0;
 	//刷新会话用户中有没有新消息
-	function check_new_showmsg(){//console.log(qid+"&uid="+uid);
-		if(ck_num>num){
-			console.log("服务器还没反馈数据过来");
-			//layer.msg("服务器反馈超时",{time:500});
-			return ;
-		}
-		$.get(getShowMsgUrl+"1&maxid="+maxid+"&uid="+uid+"&num="+num,function(res){			
-			if(res.code!=0){				
-				layer.alert('页面加载失败,请刷新当前网页');
+	function check_new_showmsg(obj){
+		if(ws_url==''){	//没有设置WS的话,就用AJAX轮询
+			if(ck_num>num){
+				console.log("服务器还没反馈数据过来");
+				//layer.msg("服务器反馈超时",{time:500});
 				return ;
 			}
-			num++;
-			ck_num = num;
-			if(res.data.length>0){	//有新的聊天内容
-				layer.closeAll();
-				need_scroll = true;
-				//vues.set_data(res.data);
-				add_msg_data(res,'new');
-			}
-			maxid = res.ext.maxid;
-			if(res.ext.lasttime<3){	//3秒内对方还在当前页面的话,就提示当前用户不要关闭当前窗口
-				if(uid>0){
-					router.$("#remind_online").html("对方正在输入中,请稍候...");
+		}
+
+		if( typeof(obj)=='object' && typeof(obj.data)=='object' && obj.data.length>0 ){		//服务端推数据, 即被动获取数据
+			var res = obj;
+			layer.closeAll();
+			need_scroll = true;
+			add_msg_data(res,'new');
+			maxid = res.ext.maxid;	//不主动获取数据的话,这个用不到
+			set_live_player(res,'cknew');	//设置视频直播的播放器
+		}else{	//客户端拉数据, 主动获取数据
+			$.get(getShowMsgUrl+"1&maxid="+maxid+"&uid="+uid+"&num="+num,function(res){			
+				if(res.code!=0){				
+					layer.alert('页面加载失败,请刷新当前网页');
+					return ;
+				}
+				num++;
+				ck_num = num;
+				if(res.data.length>0){	//有新的聊天内容
+					layer.closeAll();
+					need_scroll = true;
+					//vues.set_data(res.data);
+					add_msg_data(res,'new');
+				}
+				maxid = res.ext.maxid;
+				if(res.ext.lasttime<3){	//3秒内对方还在当前页面的话,就提示当前用户不要关闭当前窗口
+					if(uid>0){
+						router.$("#remind_online").html("对方正在输入中,请稍候...");
+					}else{
+						router.$("#remind_online").html("有用户在线");
+					}
+					router.$("#remind_online").show();
 				}else{
-					router.$("#remind_online").html("有用户在线");
+					router.$("#remind_online").hide();
 				}
-				router.$("#remind_online").show();
-			}else{
-				router.$("#remind_online").hide();
-			}
-			set_live_player(res,'cknew');	//设置视频直播的播放器
-		});
-		ck_num++;
+				set_live_player(res,'cknew');	//设置视频直播的播放器
+			});
+			ck_num++;
+		}
 	}
 
 	//设置视频直播的播放器
@@ -329,42 +425,6 @@ loader.define(function(require,exports,module) {
 		}
 	}
 	
-	//加载到第一页成功后,就获得了相关数据,才好进行其它的操作
-	function load_first_page(res){
-		maxid = res.ext.maxid;
-
-		quninfo = res.ext.qun_info;	//圈子信息
-		window.store.set("quninfo",quninfo);
-		//vues.set_quninfo(quninfo);
-		router.$("#send_user_name").html(quninfo.title);
-
-		qun_userinfo = res.ext.qun_userinfo;	//当前圈子用户信息 不存的话,就是为空即==''
-		userinfo = res.ext.userinfo;	//当前用户登录信息
-		head_menu(uid,quninfo,qun_userinfo,userinfo);
-		
-		setTimeout(function(){
-			set_live_player(res);	//设置视频直播的播放器
-
-			if(have_load_live_player==true){	//直播的时候,就不弹出签到了,影响界面布局
-				$.get("/index.php/p/signin-api-get_cfg/id/"+quninfo.id+".html",function(res){
-					if(res.code==0){
-						if(res.data.today_have_signin==true){
-							console.log('今天已经签到过了');
-						}else{
-							router.loadPart({
-								id: "#hack_signin",
-								url: "/public/static/libs/bui/pages/signin/pop.html?fdd",
-							}).then(function (module) {
-								module.api(quninfo,qun_userinfo,userinfo,res.data);
-							});
-						}					
-					}
-				});			
-			}
-
-			pageview.weixin_share();
-		},1000);
-	}
 
 	//加载更多的会话记录
 	function showMoreMsg(uid){
@@ -513,17 +573,24 @@ loader.define(function(require,exports,module) {
 			'content':content,
 			'send_to':touser.uid
 			},function(res){
+				
+				if(ws_url==''){	//没有设置WS的话,就用AJAX轮询
+					clearInterval(chat_timer);
+					chat_timer = setInterval(function() {
+						check_new_showmsg();
+					}, 1500);	//互动之后,加快刷新,重新setInterval是兼容之前任务已死掉
+				}
+
+				if(ws_stop==true){	//如果中断了,就要重连
+					pageview.ws_connect();
+				}
 
-				clearInterval(chat_timer);
-				chat_timer = setInterval(function() {
-					check_new_showmsg();
-				}, 1500);	//互动之后,加快刷新,重新setInterval是兼容之前任务已死掉
 
 				if(res.code==0){
 					router.$(".chatInput").val('');
 					router.$(".hack_wrap").hide();
 					router.$(".face_wrap").hide();
-					layer.msg('发送成功');
+					//layer.msg('发送成功');
 				}else{
 					router.$("#btnSend").removeClass("disabled").addClass("primary");
 					layer.alert('发送失败:'+res.msg);
@@ -877,6 +944,8 @@ loader.define(function(require,exports,module) {
 				set_user_name(uid);	//设置当前会话的用户名
 			}
 		}
+
+
     })
 
     // 初始化

+ 1 - 1
template/member_style/default/member/msg/pc_index.htm

@@ -363,7 +363,7 @@ var FriendActUrl = "{:urls('member/wxapp.friend/act')}";			//添加,删除好友
 
 <script type="text/javascript" src="__STATIC__/libs/amazeui/js/amazeui.min.js"></script>
 <script type="text/javascript" src="__STATIC__/libs/amazeui/js/zUI.js"></script>
-<script type="text/javascript" src="__STATIC__/libs/amazeui/js/wechat.js?"></script>
+<script type="text/javascript" src="__STATIC__/libs/amazeui/js/wechat.js?998"></script>
 <script type="text/javascript" src="__STATIC__/libs/ckplayer/ckplayer.js"></script>
 
 </body>