Exemplo n.º 1
0
        /// <summary>群组消息
        /// </summary>
        public static void SendGroup(string path, int gid, string msg)
        {
            OnLineData onlinedata = OnLineData.GetReleaseModelReadOnly();

            try
            {
                Group g = null;
                if (onlinedata.Gid_Groups.TryGetValue(gid, out g))
                {
                    foreach (var i in g.Users)
                    {
                        foreach (var j in i.Value.Clients)
                        {
                            WebSocket sock = null;
                            if (WebSockets.TryGetValue(j.Value.ID, out sock))
                            {
                                sock.Send(string.Format(@"request {0}

guid:1

{1}", path, msg));
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
        }
Exemplo n.º 2
0
        private static OnLineData GetReadWriteModel()
        {
            string     str  = Newtonsoft.Json.JsonConvert.SerializeObject(OnLineData._releaseObj);
            OnLineData _obj = Newtonsoft.Json.JsonConvert.DeserializeObject <OnLineData>(str);

            return(_obj);
        }
Exemplo n.º 3
0
        /// <summary>发送给个人用户
        /// </summary>
        public static void SendUser(string path, int uid, string msg)
        {
            OnLineData onlinedata = OnLineData.GetReleaseModelReadOnly();

            try
            {
                User u = null;
                if (onlinedata.Uid_Users.TryGetValue(uid, out u))
                {
                    foreach (var i in u.Clients.Values)
                    {
                        WebSocket sock = null;
                        if (WebSockets.TryGetValue(i.ID, out sock))
                        {
                            sock.Send(string.Format(@"request {0}

guid:1

{1}", path, msg));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
        }
Exemplo n.º 4
0
 public static void Edit(Func <OnLineData, bool> func)
 {
     lock (typeof(OnLineData))
     {
         OnLineData obj = OnLineData.GetReadWriteModel();
         bool       b   = func(obj);
         if (b)
         {
             string     str  = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
             OnLineData _obj = Newtonsoft.Json.JsonConvert.DeserializeObject <OnLineData>(str);
             OnLineData._releaseStr = str;
             OnLineData._releaseObj = _obj;
         }
     }
 }
Exemplo n.º 5
0
        /// <summary>广播消息
        /// </summary>
        public static void SendBroadCast(string path, string msg)
        {
            OnLineData onlinedata = OnLineData.GetReleaseModelReadOnly();

            try
            {
                List <WebSocket> list = WebSockets.Values.ToList();
                foreach (var i in list)
                {
                    i.Send(string.Format(@"request {0}
guid:1

{1}", path, msg));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
        }
Exemplo n.º 6
0
        /// <summary>用户客户端上线
        /// </summary>
        protected override void OnOpen()
        {
            //进入锁之前将数据准备好
            string userlogin = Context.QueryString["user"];
            string password  = Context.QueryString["pwd"];

            DBUtil.IDbAccess iDb = Util.iDb_read;

            //准备用户信息
            DataTable dt_user = iDb.GetDataTable(string.Format("select * from CHAT_USER where LOGINNAME={0} and PWD = {1}", iDb.paraPrefix + "uname", iDb.paraPrefix + "upwd"), new IDbDataParameter[] { iDb.CreatePara("uname", userlogin), iDb.CreatePara("upwd", password) });

            if (dt_user.Rows.Count == 0)
            {
                try
                {
                    Context.WebSocket.Send(string.Format("登录失败:用户或密码错误"));
                    try
                    {
                        Close();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        Console.WriteLine(ex.StackTrace);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine(ex.StackTrace);
                }
                return;
            }
            //构造客户端对象
            Client client = new Client();

            client.ID        = ID;
            client.StartTime = DateTime.Now;
            client.LOGINNAME = userlogin;
            client.UNAME     = dt_user.Rows[0]["UNAME"].ToString();
            client.USERID    = int.Parse(dt_user.Rows[0]["ID0"].ToString());

            //添加连接对象
            WebSockets.TryAdd(ID, Context.WebSocket);

            //准备群组用户群组对象
            DataTable dt_user_group = iDb.GetDataTable(string.Format("select CHAT_GROUP.* from CHAT_USER_GROUP left join CHAT_GROUP on CHAT_USER_GROUP.GID=CHAT_GROUP.ID0 where USERID='{0}'", client.USERID));

            OnLineData.Edit(online =>
            {
                //用户对象
                User user = null;
                online.Link_Clients.Add(ID, client);

                if (!online.Uid_Users.TryGetValue(client.USERID, out user))
                {
                    //当前用户的第一个客户端进行登录
                    user           = new User();
                    user.Name      = dt_user.Rows[0]["UNAME"].ToString();
                    user.ID0       = int.Parse(dt_user.Rows[0]["ID0"].ToString());
                    user.LoginName = dt_user.Rows[0]["LOGINNAME"].ToString();
                    user.Clients.Add(client.ID, client);
                    online.Uid_Users.Add(user.ID0, user);
                    online.Link_Users.Add(ID, user);

                    //构造群组对象
                    if (dt_user_group.Rows.Count > 0)
                    {
                        int count = dt_user_group.Rows.Count;
                        for (int i = 0; i < count; i++)
                        {
                            int gid = int.Parse(dt_user_group.Rows[i]["ID0"].ToString());
                            Group g;
                            if (!online.Gid_Groups.TryGetValue(gid, out g))
                            {
                                //初次建立群组对象
                                g      = new Group();
                                g.Name = dt_user_group.Rows[i]["GNAME"].ToString();
                                g.ID0  = gid;
                                g.Users.Add(user.ID0, user);
                                online.Gid_Groups.Add(g.ID0, g);
                            }
                            else
                            {
                                //已经存在这个群组对象
                                if (!g.Users.ContainsKey(user.ID0))
                                {
                                    //不包含这个用户
                                    g.Users.Add(user.ID0, user);
                                }
                            }
                        }
                    }
                }
                else
                {
                    //当前用户的多个用户端登录
                    user.Clients.Add(client.ID, client);
                    online.Link_Users.Add(ID, user);
                }
                return(true);
            });
            //广播用户上线通知
            SendBroadCast("/BroadUserOnLine", Newtonsoft.Json.JsonConvert.SerializeObject(new
            {
                type      = "BroadUserOnLine",
                loginname = client.LOGINNAME
            }));
        }
Exemplo n.º 7
0
        /// <summary>用户客户端下线
        /// </summary>
        protected override void OnClose(CloseEventArgs e)
        {
            //移除连接对象
            WebSocket socket;

            WebSockets.TryRemove(ID, out socket);
            User user = null;
            //是否移除用户
            bool isRemoveUser = false;

            DBUtil.IDbAccess iDb = Util.iDb_read;
            OnLineData.Edit(online =>
            {
                Client client;
                if (online.Link_Clients.TryGetValue(ID, out client))
                {
                    //1.移除客户端
                    online.Link_Clients.Remove(ID);
                }
                if (online.Link_Users.TryGetValue(ID, out user))
                {
                    //2.移除用户
                    online.Link_Users.Remove(ID);
                }
                if (user != null)
                {
                    if (online.Uid_Users.ContainsKey(user.ID0))
                    {
                        User user2 = online.Uid_Users[user.ID0];
                        if (user2.Clients.ContainsKey(ID))
                        {
                            //3.移除用户中的客户端
                            user2.Clients.Remove(ID);
                        }
                        if (user2.Clients.Count == 0)
                        {
                            //4.如果用户没有了客户端就移除这个用户
                            online.Uid_Users.Remove(user.ID0);
                            isRemoveUser = true;
                        }
                    }
                }
                if (isRemoveUser)
                {
                    List <int> _remove_group_keys = new List <int>();
                    foreach (var i in online.Gid_Groups)
                    {
                        if (i.Value.Users.ContainsKey(user.ID0))
                        {
                            //5.从组中移出用户
                            i.Value.Users.Remove(user.ID0);
                        }
                        if (i.Value.Users.Count == 0)
                        {
                            //6.如果组中已没有用户,就将这个组移除,记住ID后面删除
                            _remove_group_keys.Add(i.Key);
                        }
                    }
                    foreach (var i in _remove_group_keys)
                    {
                        online.Gid_Groups.Remove(i);
                    }
                }
                return(true);
            });
            OnLineData onlinedata = OnLineData.GetReleaseModelReadOnly();

            if (user != null && isRemoveUser)
            {
                //广播下线消息(存在这个用户并且这个用户的客户端全部下线后)
                //仅将消息发送给这个用户的好友
                try
                {
                    DataTable dt = iDb.GetDataTable("select * from CHAT_USER_RELATION a left join CHAT_USER b on a.USERID2=b.ID0 where a.USERID1='" + user.ID0 + "'");
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        int userid = int.Parse(dt.Rows[i]["USERID2"].ToString());
                        SendUser("/BroadUserOffLine", userid, Newtonsoft.Json.JsonConvert.SerializeObject(new { uid = user.ID0 }));
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine(ex.StackTrace);
                }
            }
        }
Exemplo n.º 8
0
        /// <summary>接收客户端消息
        /// </summary>
        protected override void OnMessage(MessageEventArgs e)
        {
            OnLineData online = OnLineData.GetReleaseModelReadOnly();
            //构造上下文环境
            BaseContext ctx = new BaseContext();

            ctx.CreateTime    = DateTime.Now;
            ctx.SocketContext = Context;
            ctx.From          = online.Link_Clients[ID];

            string str   = e.Data;
            int    index = str.IndexOf("\n");

            string[] arr = str.Substring(0, index).Split(' ');
            if (arr[0] == "request")
            {
                //客户端请求消息
                string path = ctx.Path = arr[1];
                str = str.Substring(index + 1);
                string[] headers = null;
                string   body    = null;
                if (str.Contains("\n\n") || str.Contains("\r\n\r\n"))
                {
                    string[] arr2 = str.Split(new string[] { "\n\n", "\r\n\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                    headers = arr2[0].Split('\r', '\n');
                    body    = arr2.Length == 2 ? arr2[1] : null;
                }
                else
                {
                    headers = str.Split('\r', '\n');
                }
                for (int i = 0; i < headers.Length; i++)
                {
                    string line = headers[i];
                    if (!line.Contains(":"))
                    {
                        continue;
                    }
                    ctx.Headers.Add(line.Split(':')[0], line.Split(':')[1]);
                }
                if (!string.IsNullOrWhiteSpace(body))
                {
                    ctx.Content = Newtonsoft.Json.JsonConvert.DeserializeObject(body);
                }
                if (_dic.ContainsKey(path))
                {
                    Result res = _dic[path](ctx);
                    if (res != null)
                    {
                        Reply(ctx, res);
                    }
                }
                else
                {
                    Reply(ctx, new Result()
                    {
                        Success = false,
                        Data    = string.Format("找不到路径:{0} 的处理逻辑!", path)
                    });
                }
            }
            else if (arr[0] == "reply")
            {
                //客户端回复消息
            }
        }
Exemplo n.º 9
0
        /// <summary>处理获取用户组织树的消息请求
        /// </summary>
        private static Result DealUserTreeMsg(BaseContext ctx)
        {
            DBUtil.IDbAccess iDb    = Util.iDb_read;
            OnLineData       online = OnLineData.GetReleaseModelReadOnly();
            int userid = ctx.From.USERID;
            //获取到这个用户加入的所有分组
            DataTable dt_user_groups = iDb.GetDataTable("select b.* from CHAT_USER_GROUP a left join CHAT_GROUP b on a.GID=b.ID0 where a.USERID='" + userid + "'");
            //获取到这个用户所有的好友和分组
            DataTable dt_users = iDb.GetDataTable("select b.*,a.INNERGID from CHAT_USER_RELATION a left join CHAT_USER b on a.USERID2=b.ID0 where a.USERID1='" + userid + "'");
            //获取这个用户所有的内部分组
            DataTable dt_inner_groups = iDb.GetDataTable("select * from CHAT_INNER_GROUP where USERID='" + userid + "' order by GORDER");

            //组装当前用户所在的群
            List <_Group> groups = new List <_Group>();
            int           i = 0, count = 0;

            for (i = 0, count = dt_user_groups.Rows.Count; i < count; i++)
            {
                _Group g = new _Group();
                g.ID0   = int.Parse(dt_user_groups.Rows[i]["ID0"].ToString());
                g.GNAME = dt_user_groups.Rows[i]["GNAME"].ToString();
                g.GDESC = dt_user_groups.Rows[i]["GDESC"].ToString();
                g.GIMG  = dt_user_groups.Rows[i]["GIMG"].ToString();
                groups.Add(g);
                //获取这个分组内的所有人员
                DataTable dt = iDb.GetDataTable("select b.* from CHAT_USER_GROUP a left join CHAT_USER b on a.USERID=b.ID0 where a.GID='" + g.ID0 + "'");

                for (int j = 0, len = dt.Rows.Count; j < len; j++)
                {
                    _User u = new _User();
                    u.ID0         = int.Parse(dt.Rows[j]["ID0"].ToString());
                    u.LOGINNAME   = dt.Rows[j]["LOGINNAME"].ToString();
                    u.UDES        = dt.Rows[j]["UDES"].ToString();
                    u.UIMG        = dt.Rows[j]["UIMG"].ToString();
                    u.ULOCATE     = dt.Rows[j]["ULOCATE"].ToString();
                    u.ULOCATENAME = dt.Rows[j]["ULOCATENAME"].ToString();
                    u.UNAME       = dt.Rows[j]["UNAME"].ToString();
                    //判断当前用户是否在线
                    if (online.Uid_Users.ContainsKey(u.ID0))
                    {
                        u.IsOnline = true;
                    }
                    g.Users.Add(u);
                }
            }
            //组装当前用户所有的分组好友
            List <_Group> inner_groups = new List <_Group>();

            for (i = 0, count = dt_inner_groups.Rows.Count; i < count; i++)
            {
                _Group g = new _Group();
                g.ID0    = int.Parse(dt_inner_groups.Rows[i]["ID0"].ToString());
                g.GNAME  = dt_inner_groups.Rows[i]["GNAME"].ToString();
                g.GORDER = int.Parse(dt_inner_groups.Rows[i]["GORDER"].ToString());
                inner_groups.Add(g);
                int j = 0, jcount = 0;
                for (j = 0, jcount = dt_users.Rows.Count; j < jcount; j++)
                {
                    int INNERGID = int.Parse(dt_users.Rows[j]["INNERGID"].ToString());
                    if (INNERGID == g.ID0)
                    {
                        _User u = new _User();
                        u.ID0         = int.Parse(dt_users.Rows[j]["ID0"].ToString());
                        u.LOGINNAME   = dt_users.Rows[j]["LOGINNAME"].ToString();
                        u.UDES        = dt_users.Rows[j]["UDES"].ToString();
                        u.UIMG        = dt_users.Rows[j]["UIMG"].ToString();
                        u.ULOCATE     = dt_users.Rows[j]["ULOCATE"].ToString();
                        u.ULOCATENAME = dt_users.Rows[j]["ULOCATENAME"].ToString();
                        u.UNAME       = dt_users.Rows[j]["UNAME"].ToString();
                        //判断当前用户是否在线
                        if (online.Uid_Users.ContainsKey(u.ID0))
                        {
                            u.IsOnline = true;
                        }
                        g.Users.Add(u);
                    }
                }
            }
            Result res = new Result();

            res.Success = true;
            res.Data    = new
            {
                groups       = groups,
                inner_groups = inner_groups
            };
            return(res);
        }