Esempio n. 1
0
 //添加聊天信息
 public void AddMessage(Message msg)
 {
     DatabaseMessage newMessage = new DatabaseMessage
     {
         Sender = msg.Sender,
         Receiver = msg.Receiver,
         Time = msg.SendTime,
         Type = msg.Type.ToString(),
         Content = msg.Content
     };
     dataContext.DatabaseMessage.InsertOnSubmit(newMessage);
     dataContext.SubmitChanges();
 }
Esempio n. 2
0
 public bool SendMessage(Message msg)
 {
     try
     {
         byte[] buffer = Encoding.Unicode.GetBytes(msg.ToString());
         streamToServer.Write(buffer, 0, buffer.Length);
         return true;
     }
     catch
     {
         return false;
     }
 }
Esempio n. 3
0
 public bool SendMessage(Message msg, NetworkStream streamToClient)
 {
     string msgString = msg.ToString();
     byte[] buffer = Encoding.Unicode.GetBytes(msgString);
     try
     {
         streamToClient.Write(buffer, 0, buffer.Length);
         return true;
     }
     catch
     {
         return false;
         throw;
     }
 }
Esempio n. 4
0
 public GroupMessageEventArgs(DateTime time, string sender, string receiver, string content)
 {
     msg = new Message(MessageType.PRIV, time, sender, receiver, content);
 }
Esempio n. 5
0
 private bool FowardTo(MessageReceivedEventArgs e, string userName, Message msg)
 {
     //检测用户是否在线
     if (!onlineUsers.Contains(userName))
     {
         //不在线,写入用户离线信息
         database.AddUserMessage(userName, msg);
         return true;
     }
     else
     {
         //在线,直接发送给目标用户
         NetworkStream targetStream = (onlineUsers[userName] as OnlineUser).StreamToRemote;
         return receiver.SendMessage(msg, targetStream);
     }
 }
Esempio n. 6
0
 private void OnNewChatCreated(Message msg)
 {
     string[] tokens = msg.Content.Split(new char[] { '|' });
     string sender = msg.Sender;
     int chatNumber = int.Parse(tokens[0]);
     string chatName = tokens[1];
     List<string> userNames = new List<string>();
     for (int i = 2; i < tokens.Length; i++)
     {
         if (!string.IsNullOrEmpty(tokens[i]))
         {
             userNames.Add(tokens[i]);
         }
     }
     if (NewChatCreated != null)
     {
         NewChatCreated(this, new NewChatEventArgs(chatNumber, chatName, sender, userNames));
     }
 }
Esempio n. 7
0
 public void SendNoResponse(Message msg)
 {
     sender.SendMessage(msg);
 }
Esempio n. 8
0
 public List<ClientUser> SearchFriend(Message msg)
 {
     sender.SendMessage(msg);
     Thread.Sleep(500);
     List<ClientUser> usersFound = new List<ClientUser>();
     for (int i = 0; i < 10; i++)
     {
         if (currentResponse == null)
         {
             Thread.Sleep(50);
             continue;
         }
         //等待响应
         if (DateTime.Compare(msg.SendTime, currentResponse.SendTime + new TimeSpan(0, 0, 0, 1, 0)) <= 0)
         {
             string[] tokens = currentResponse.Content.Split(new char[] { '|' });
             string userName = string.Empty, nickName = string.Empty, email = string.Empty;
             int age = 18;
             GenderOption gender = GenderOption.Male;
             for (int j = 0; j < tokens.Length; j++)
             {
                 if (tokens[j].Trim() == "empty")
                 {
                     break;
                 }
                 if (string.IsNullOrEmpty(tokens[j]))
                 {
                     break;
                 }
                 if (j % 5 == 0)
                 {
                     userName = tokens[j];
                 }
                 else if (j % 5 == 1)
                 {
                     nickName = tokens[j];
                 }
                 else if (j % 5 == 2)
                 {
                     gender = (GenderOption)Enum.Parse(typeof(GenderOption), tokens[j]);
                 }
                 else if (j % 5 == 3)
                 {
                     age = int.Parse(tokens[j]);
                 }
                 else
                 {
                     email = tokens[j];
                     ClientUser newUser = new ClientUser(userName, nickName, age, gender, email);
                     usersFound.Add(newUser);
                 }
             }
         }
         else
         {
             Thread.Sleep(50);
         }
         return usersFound;
     }
     return usersFound;
 }
Esempio n. 9
0
 //属于命令UserSearchCommand
 private void SearchUser(object obj)
 {
     string sender = dataService.UserName;
     string userName = search;
     string nickName = search;
     string gender = GenderSelected;
     int age = AgeSelected;
     string ageString;
     if (age == -1)
     {
         ageString = "Unlimited";
     }
     else
     {
         ageString = age.ToString();
     }
     string content = userName + "|" + nickName + "|" + gender + "|" + ageString;
     Message msg = new Message(MessageType.FRIENDSEARCH, sender, content);
     var found = dataService.SendFriendSearchMessage(msg);
     FriendsFound.Clear();
     //注意为空情况
     if (found.Count == 0)
     {
         MessageBox.Show("没有找到用户");
     }
     else if (found.Count == 1 && found.First().UserName == dataService.UserName)
     {
         MessageBox.Show("没有找到用户");
     }
     else
     {
         foreach (var user in found)
         {
             if (user.UserName != dataService.UserName)
             {
                 FriendsFound.Add(user);
             }
         }
     }
 }
Esempio n. 10
0
 private void SendGroupChatList(MessageReceivedEventArgs e, string userName)
 {
     //格式CREATECHAT|time|SERVER|chatnumber|chatname|username1|...
     List<ServerChat> allChats = database.GetUserGroupChats(userName);
     foreach (var chat in allChats)
     {
         StringBuilder sb = new StringBuilder();
         sb.AppendFormat("{0}|{1}|", chat.ChatNumber, chat.ChatName);
         foreach (string name in chat.ChatUserNames)
         {
             sb.AppendFormat("{0}|", name);
         }
         Message msg = new Message(MessageType.CREATECHAT, "SERVER", sb.ToString());
         FowardTo(e, userName, msg);
         Thread.Sleep(400);
     }
 }
Esempio n. 11
0
 //发送好友信息列表
 private void SendFriendList(MessageReceivedEventArgs e, string userName)
 {
     //格式FRIENDLIST|time|SERVER|username1|nickname1|gender1|age1|email1|...
     //注意为空的情况
     StringBuilder sb = new StringBuilder();
     OnlineUser currentUser = onlineUsers[userName] as OnlineUser;
     string content;
     if (currentUser.FriendNames == null || currentUser.FriendNames.Count == 0)
     {
         return;
     }
     else
     {
         foreach (string name in currentUser.FriendNames)
         {
             ServerUser currentFriend = database.GetUser(name);
             sb.AppendFormat("{0}|{1}|{2}|{3}|{4}|", currentFriend.UserName,
                 currentFriend.NickName, currentFriend.Gender.ToString(),
                 currentFriend.Age, currentFriend.Email);
         }
         content = sb.ToString();
         Message newMessage = new Message(MessageType.FRIENDLIST, "SERVER", content);
         FowardTo(e, userName, newMessage);
     }
 }
Esempio n. 12
0
 private void RespondOK(MessageReceivedEventArgs e)
 {
     Message respondMessage = new Message(MessageType.OK);
     receiver.SendMessage(respondMessage, e.StreamToRemote);
 }
Esempio n. 13
0
 private void RespondInvalid(MessageReceivedEventArgs e)
 {
     Message respondMessage = new Message(MessageType.INVALID);
     receiver.SendMessage(respondMessage, e.StreamToRemote);
 }
Esempio n. 14
0
 private void ProcessMessage(object sender, MessageReceivedEventArgs e)
 {
     string originalString = e.Content;
     //从string获取Message
     Message msg = GenerateMessage(originalString);
     //注册
     if (msg.Type == MessageType.REGISTER)
     {
         //数据库中有此用户,注册失败
         if (database.ContainsUser(msg.Sender))
         {
             RespondInvalid(e);
         }
         //数据库中无此用户,注册成功
         else
         {
             RespondOK(e);
             AddUserToDatabase(database, msg.Content);
         }
     }
     //登录
     else if (msg.Type == MessageType.LOGIN)
     {
         string userName = msg.Sender;
         string password = msg.Content;
         if (CheckIdentity(userName, password) && !onlineUsers.Contains(userName))
         {
             //回应ok
             RespondOK(e);
             //将用户加入在线用户表
             ServerUser fetchedServerUser = database.GetUser(userName);
             OnlineUser newOnlineUser = new OnlineUser(fetchedServerUser, e.StreamToRemote);
             onlineUsers.Add(userName, newOnlineUser);
             //发送用户好友列表
             SendFriendList(e, userName);
             Thread.Sleep(100);
             //发送用户群聊列表
             SendGroupChatList(e, userName);
             //发送用户在线好友列表,发送给在线好友JOIN信息
             //SendOnlineFriendList(e, userName);
             Thread.Sleep(200);
             //发送用户离线时收到的信息
             SendOfflineMessage(e, userName);
             //触发在线用户改变事件
             if (OnlineUserChanged != null)
             {
                 OnlineUserChanged(this, new OnlineUserChangedEventArgs(newOnlineUser.UserName, "online"));
             }
         }
         else
         {
             RespondInvalid(e);
         }
     }
     //查询好友
     else if (msg.Type == MessageType.FRIENDSEARCH)
     {
         string[] keyWords = msg.Content.Split(new char[] { '|' });
         string userName = keyWords[0];
         string nickName = keyWords[1];
         string gender = keyWords[2]; //注意此处gender为string以方便查询
         int age = -1;
         if (keyWords[3].Trim().ToLower() != "unlimited")
         {
             age = int.Parse(keyWords[3].Trim());
         }
         List<ServerUser> usersFound = database.SearchUser(userName, nickName, gender, age);
         if (usersFound.Count == 0)
         {
             Message newMessage = new Message(MessageType.FRIENDSEARCH, "SERVER", "empty");
             FowardTo(e, msg.Sender, newMessage);
         }
         else
         {
             StringBuilder sb = new StringBuilder();
             foreach (ServerUser userFound in usersFound)
             {
                 string newUserName = userFound.UserName;
                 string newNickName = userFound.NickName;
                 string newGender = userFound.Gender.ToString();
                 string newAge = userFound.Age.ToString();
                 string newEmail = userFound.Email;
                 sb.AppendFormat("{0}|{1}|{2}|{3}|{4}|", newUserName, newNickName,
                     newGender, newAge, newEmail);
             }
             string newContent = sb.ToString();
             Message newMessage = new Message(MessageType.FRIENDSEARCH, "SERVER", newContent);
             FowardTo(e, msg.Sender, newMessage);
         }
     }
     //私聊,转发给目标用户,写入总聊天记录
     else if (msg.Type == MessageType.PRIV)
     {
         bool IsSuccess = FowardTo(e, msg.Receiver, msg);
         if (IsSuccess)
         {
             database.AddMessage(msg);
             RespondOK(e);
         }
         else
         {
             RespondInvalid(e);
         }
     }
     //群聊,获取群信息,写入总聊天记录,转发给目标用户
     else if (msg.Type == MessageType.GROUP)
     {
         int chatNumber = int.Parse(msg.Receiver);
         ServerChat targetChat = database.GetChat(chatNumber);
         foreach (string userName in targetChat.ChatUserNames)
         {
             if (userName != msg.Sender)
             {
                 try
                 {
                     FowardTo(e, userName, msg);
                 }
                 catch
                 {
                     RespondInvalid(e);
                 }
             }
         }
         database.AddMessage(msg);
         RespondOK(e);
     }
     //用户离线
     else if (msg.Type == MessageType.LEAVE)
     {
         string userName = msg.Sender;
         OnlineUser currentUser = onlineUsers[userName] as OnlineUser;
         //向在线好友发送离线消息
         foreach (string friendName in currentUser.FriendNames)
         {
             if (onlineUsers.Contains(friendName))
             {
                 FowardTo(e, friendName, msg);
             }
         }
         //触发在线用户改变事件
         if (OnlineUserChanged != null)
         {
             OnlineUserChanged(this,
                 new OnlineUserChangedEventArgs(onlineUsers[userName] as OnlineUser, "offline"));
         }
         //是否要在此关闭用户连接?
         //将用户移出在线用户列表
         onlineUsers.Remove(userName);
     }
     //好友申请消息
     else if (msg.Type == MessageType.FRIENDREQUEST)
     {
         MakeFriend(msg.Sender, msg.Receiver);
         bool IsSuccess = FowardTo(e, msg.Receiver, msg);
         if (IsSuccess)
         {
             database.AddMessage(msg);
             RespondOK(e);
         }
         else
         {
             RespondInvalid(e);
         }
     }
     //创建群聊
     else if (msg.Type == MessageType.CREATECHAT)
     {
         ServerChat newChat = new ServerChat(msg.Receiver);
         string[] tokens = msg.Content.Split(new char[] { '|' });
         foreach (string token in tokens)
         {
             if (!string.IsNullOrEmpty(token))
             {
                 newChat.AddUserName(token.Trim());
             }
         }
         //在数据库中创建群聊
         try
         {
             database.AddChat(newChat);
         }
         catch
         {
             RespondInvalid(e);
         }
         //将信息转发给群聊参与者
         StringBuilder sb = new StringBuilder();
         sb.AppendFormat("{0}|", newChat.ChatNumber.ToString());
         sb.AppendFormat("{0}|", newChat.ChatName);
         foreach (var user in newChat.ChatUserNames)
         {
             sb.AppendFormat("{0}|", user);
         }
         Message msgToClient = new Message(MessageType.CREATECHAT, msg.SendTime,
             msg.Sender, sb.ToString());
         bool IsSuccess = true;
         foreach (string userName in newChat.ChatUserNames)
         {
             IsSuccess = FowardTo(e, userName, msgToClient);
         }
         //回应
         if (IsSuccess)
         {
             RespondOK(e);
         }
         else
         {
             RespondOK(e);
         }
     }
     //离开群聊
     else if (msg.Type == MessageType.LEAVECHAT)
     {
         int chatNumber = int.Parse(msg.Content);
         string userName = msg.Sender;
         //在数据库中更新群聊信息
         try
         {
             database.DeleteChatUser(chatNumber, userName);
         }
         catch
         {
             RespondInvalid(e);
         }
         //向群聊者推送离开信息
         ServerChat currentChat = database.GetChat(chatNumber);
         bool IsSuccess = true;
         foreach (string name in currentChat.ChatUserNames)
         {
             if (name != userName)
             {
                 IsSuccess = FowardTo(e, name, msg);
             }
         }
         if (IsSuccess)
         {
             RespondOK(e);
         }
         else
         {
             RespondOK(e);
         }
     }
 }
Esempio n. 15
0
        private Message GenerateMessage(string msgString)
        {
            string[] tokens = msgString.Split(new char[] { '|' });
            DateTime time = DateTime.Parse(tokens[1]);
            if (tokens[0].ToUpper() == "LOGIN")
            {
                Message msg = new Message(MessageType.LOGIN, time, tokens[2], tokens[3]);
                return msg;
            }
            else if (tokens[0].ToUpper() == "REGISTER")
            {
                StringBuilder sb = new StringBuilder();
                for (int i = 2; i < tokens.Length; i++)
                {
                    sb.AppendFormat("{0}|", tokens[i]);
                }
                Message msg = new Message(MessageType.REGISTER, time,
                    tokens[2], sb.ToString());
                return msg;
            }
            else if (tokens[0].ToUpper() == "FRIENDSEARCH")
            {
                string sender = tokens[2];
                StringBuilder sb = new StringBuilder();
                for (int i = 3; i < tokens.Length; i++)
                {
                    sb.AppendFormat("{0}|", tokens[i]);
                }
                Message msg = new Message(MessageType.FRIENDSEARCH, time, sender,
                    sb.ToString());
                return msg;
            }
            else if (tokens[0].ToUpper() == "FRIENDREQUEST")
            {
                string sender = tokens[2];
                string receiver = tokens[3];
                string content = tokens[4];
                Message msg = new Message(MessageType.FRIENDREQUEST, time, sender, receiver, content);
                return msg;
            }
            else if (tokens[0].ToUpper() == "PRIV")
            {
                string sender = tokens[2];
                string receiver = tokens[3];
                string content = tokens[4];
                Message msg = new Message(MessageType.PRIV, time, sender, receiver, content);
                return msg;
            }
            else if (tokens[0].ToUpper() == "GROUP")
            {
                string sender = tokens[2];
                string receiver = tokens[3];
                string content = tokens[4];
                Message msg = new Message(MessageType.GROUP, time, sender, receiver, content);
                return msg;
            }
            //离线格式:LEAVE|time|sender
            else if (tokens[0].ToUpper() == "LEAVE")
            {
                string sender = tokens[2];
                Message msg = new Message(MessageType.LEAVE, time, sender, "");
                return msg;
            }

            else if (tokens[0].ToUpper() == "CREATECHAT")
            {
                string sender = tokens[2];
                string chatName = tokens[3];
                StringBuilder sb = new StringBuilder();
                for (int i = 4; i < tokens.Length; i++)
                {
                    sb.AppendFormat("{0}|", tokens[i]);
                }
                Message msg = new Message(MessageType.CREATECHAT, time, sender, chatName, sb.ToString());
                return msg;
            }

            else if (tokens[0].ToUpper() == "LEAVECHAT")
            {
                string sender = tokens[2];
                string chatNumber = tokens[3];
                Message msg = new Message(MessageType.LEAVECHAT, time, sender, chatNumber);
                return msg;
            }

            //TODO: other circumstences
            else
            {
                Message msg = new Message();
                return msg;
            }
        }
Esempio n. 16
0
 //属于AddFriendCommand
 private void AddFriend(object obj)
 {
     string targetName = (obj as ClientUser).UserName;
     //首先判断是否已经是好友
     var currentUserFriends = dataService.GetAllFriends();
     var searchedUser = from u in currentUserFriends
                        where u.UserName == targetName
                        select u;
     if (searchedUser.Count() != 0)
     {
         MessageBox.Show("你与此用户已是好友");
         return;
     }
     Message msg = new Message(MessageType.FRIENDREQUEST, dataService.UserName, targetName
         , string.Empty);
     ResponseType response = dataService.SendAddFriendMessage(msg);
     if (response == ResponseType.OK)
     {
         ClientUser newFriend = obj as ClientUser;
         Utilities.Messenger.Default.Send(new Messages.NewFriendMessage(newFriend));
         MessageBox.Show("添加好友成功");
     }
     else if (response == ResponseType.INVALID)
     {
         MessageBox.Show("添加好友失败");
     }
     else
     {
         MessageBox.Show("网络错误");
     }
 }
Esempio n. 17
0
 //发送在线好友列表
 private void SendOnlineFriendList(MessageReceivedEventArgs e, string userName)
 {
     //格式ONLINELIST|time|SERVER|username1|username2|...
     //注意为空的情况
     StringBuilder sb = new StringBuilder();
     OnlineUser currentUser = onlineUsers[userName] as OnlineUser;
     if (currentUser.FriendNames.Count != 0)
     {
         foreach (string friendName in currentUser.FriendNames)
         {
             if (onlineUsers.Contains(friendName))
             {
                 sb.AppendFormat("{0}|", friendName);
                 //发送上线信息,格式为JOIN|time|username
                 Message msgToFriend = new Message(MessageType.JOIN, userName, string.Empty);
                 FowardTo(e, friendName, msgToFriend);
             }
         }
         string content = sb.ToString();
         Message newMessage = new Message(MessageType.ONLINELIST, "SERVER", content);
         FowardTo(e, userName, newMessage);
     }
 }
Esempio n. 18
0
 private void LogIn(object obj)
 {
     if (!isConnected)
     {
         if (!dataService.Connect(IPAddress.Parse(ipAddress), portNumber))
         {
             MessageBox.Show("无法连接至服务器");
             isConnected = false;
         }
         else
         {
             isConnected = true;
         }
     }
     string passwordEncripted = GetMD5();
     Message logInMessage = new Message(MessageType.LOGIN, DateTime.Now, UserName, passwordEncripted);
     ResponseType logInResponse = dataService.SendLogInMessage(logInMessage);
     if (logInResponse == ResponseType.OK)
     {
         SaveSettings();
         dataService.LoadUserData(userName);
         dataService.UserName = UserName;
         Main mainWindow = new Main(dataService);
         this._closeAction.Invoke();
     }
     else if (logInResponse == ResponseType.INVALID)
     {
         MessageBox.Show("用户名或密码错误");
     }
     else
     {
         MessageBox.Show("网络错误");
     }
 }
Esempio n. 19
0
        //属于命令SendMessageCommand
        private void SendMessage(object obj)
        {
            selectedChat.ChatLogs.Add(new ChatLog(DateTime.Now, dataService.UserName, textEntered));
            if (selectedChat is PrivateChat)
            {
                string receiver = (selectedChat as PrivateChat).RemoteUser.UserName;
                Message msg = new Message(MessageType.PRIV, dataService.UserName, receiver, textEntered);
                dataService.SendChatMessage(msg);
            }
            else
            {
                string groupNumber = (selectedChat as GroupChat).ChatNumber.ToString();
                Message msg = new Message(MessageType.GROUP, dataService.UserName, groupNumber, textEntered);
                dataService.SendChatMessage(msg);
            }

            TextEntered = string.Empty;
        }
Esempio n. 20
0
 public ResponseType Send(Message msg)
 {
     sender.SendMessage(msg);
     Thread.Sleep(500);
     for (int i = 0; i < 10; i++)
     {
         Debug.WriteLine("checked {0}", DateTime.Now);
         if (currentResponse == null)
         {
             Thread.Sleep(50);
             continue;
         }
         //等待响应
         if (msg.SendTime.CompareTo(currentResponse.SendTime + new TimeSpan(0,0,0,1,0)) <= 0)
         {
             Debug.WriteLine("Response handled {0}", DateTime.Now);
             switch (currentResponse.Type)
             {
                 case MessageType.INVALID:
                     return ResponseType.INVALID;
                 case MessageType.OK:
                     return ResponseType.OK;
                 case MessageType.ERROR:
                     return ResponseType.ERROR;
                 default:
                     return ResponseType.ERROR;
             }
         }
         else
         {
             Thread.Sleep(50);
         }
     }
     Debug.WriteLine("No response {0}", DateTime.Now);
     return ResponseType.ERROR;
 }
Esempio n. 21
0
 //添加用户聊天信息
 public void AddUserMessage(string userName, Message msg)
 {
     DatabaseUser targetUser = (from u in dataContext.DatabaseUser
                                where u.UserName == userName
                                select u).Single();
     DatabaseUserMessage newUserMessage = new DatabaseUserMessage()
     {
         Time = msg.SendTime,
         Sender = msg.Sender,
         Receiver = msg.Receiver,
         Content = msg.Content,
         Type = msg.Type.ToString()
     };
     targetUser.DatabaseUserMessage.Add(newUserMessage);
     dataContext.SubmitChanges();
 }
Esempio n. 22
0
 private Message GenerateMessage(string orginalString)
 {
     string[] tokens = orginalString.Split(new char[] { '|' });
     DateTime time = DateTime.Parse(tokens[1]);
     Message msg;
     StringBuilder sb;
     switch (tokens[0].ToUpper())
     {
         case "OK":
             msg = new Message(MessageType.OK, time);
             break;
         case "INVALID":
             msg = new Message(MessageType.INVALID, time);
             break;
         case "ERROR":
             msg = new Message(MessageType.ERROR, time);
             break;
         case "PRIV":
             sb = new StringBuilder();
             for (int i = 4; i < tokens.Length; i++)
             {
                 sb.AppendFormat("{0} ", tokens[i]);
             }
             msg = new Message(MessageType.PRIV, time, tokens[2], tokens[3], sb.ToString());
             break;
         case "GROUP":
             sb = new StringBuilder();
             for (int i = 4; i < tokens.Length; i++)
             {
                 sb.AppendFormat("{0} ", tokens[i]);
             }
             msg = new Message(MessageType.GROUP, time, tokens[2], tokens[3], sb.ToString());
             break;
         case "ONLINELIST":
         case "FRIENDLIST":
             sb = new StringBuilder();
             for (int i = 3; i < tokens.Length; i++)
             {
                 sb.AppendFormat("{0}|", tokens[i]);
             }
             msg = new Message(MessageType.FRIENDLIST, time, "SERVER", sb.ToString());
             break;
         case "JOIN":
             msg = new Message(MessageType.JOIN, time, tokens[2], string.Empty);
             break;
         case "LEAVE":
             msg = new Message(MessageType.LEAVE, time, tokens[2], string.Empty);
             break;
         case "FRIENDREQUEST":
             sb = new StringBuilder();
             for (int i = 4; i < tokens.Length; i++)
             {
                 sb.AppendFormat("{0} ", tokens[i]);
             }
             msg = new Message(MessageType.FRIENDREQUEST, time, tokens[2], tokens[3], sb.ToString());
             break;
         case "FRIENDSEARCH":
             sb = new StringBuilder();
             for (int i = 3; i < tokens.Length; i++)
             {
                 sb.AppendFormat("{0}|", tokens[i]);
             }
             msg = new Message(MessageType.FRIENDSEARCH, time, "SERVER", sb.ToString());
             break;
         case "CREATECHAT":
             sb = new StringBuilder();
             for (int i = 3; i < tokens.Length; i++)
             {
                 sb.AppendFormat("{0}|", tokens[i]);
             }
             msg = new Message(MessageType.CREATECHAT, time, tokens[2], sb.ToString());
             break;
         case "LEAVECHAT":
             msg = new Message(MessageType.LEAVECHAT, time, tokens[2], tokens[3]);
             break;
         default:
             msg = new Message(MessageType.ERROR, time);
             break;
     }
     return msg;
 }
Esempio n. 23
0
 //获得用户离线消息并清空离线消息
 public List<Message> FetchUserMessage(string userName)
 {
     List<Message> newUserMessages = new List<Message>();
     var fetchedUser = (from u in dataContext.DatabaseUser
                        where u.UserName == userName
                        select u).Single();
     var fetchedUserMessage = from m in fetchedUser.DatabaseUserMessage
                              select m;
     foreach (DatabaseUserMessage msg in fetchedUserMessage)
     {
         MessageType msgType = (MessageType)Enum.Parse(typeof(MessageType), msg.Type);
         Message newMessage = new Message(msgType, msg.Time, msg.Sender, msg.Receiver, msg.Content);
         newUserMessages.Add(newMessage.Clone() as Message);
     }
     foreach (DatabaseUserMessage msg in fetchedUserMessage)
     {
         dataContext.DatabaseUserMessage.DeleteOnSubmit(msg);
     }
     dataContext.SubmitChanges();
     return newUserMessages;
 }
Esempio n. 24
0
 /// <summary>
 /// 对收到信息事件的处理
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void ProcessMessage(object sender, MessageReceivedEventArgs e)
 {
     string orginalString = e.Content;
     Message msg = GenerateMessage(orginalString);
     switch (msg.Type)
     {
         case MessageType.ONLINELIST:
             string[] receivedUserNames = msg.Content.Split(new char[] { '|' });
             foreach (string receivedUserName in receivedUserNames)
             {
                 UpdateUserOnline(receivedUserName);
             }
             break;
         case MessageType.JOIN:
             UpdateUserOnline(msg.Content);
             break;
         case MessageType.LEAVE:
             UpdateUserOffline(msg.Sender);
             break;
         case MessageType.FRIENDLIST:
             UpdateFriendInformation(msg.Content);
             break;
         case MessageType.PRIV:
             //私聊,触发私聊信息事件
             if (PrivateMessageReceived != null)
             {
                 PrivateMessageReceived(this,
                     new PrivateMessageEventArgs(msg.SendTime, msg.Sender
                     , msg.Receiver, msg.Content));
             }
             break;
         case MessageType.GROUP:
             //群聊,触发群聊信息事件
             if (GroupMessageReceived != null)
             {
                 GroupMessageReceived(this,
                     new GroupMessageEventArgs(msg.SendTime, msg.Sender
                     , msg.Receiver, msg.Content));
             }
             break;
         case MessageType.FRIENDREQUEST:
             //好友申请,触发事件
             if (FriendRequestReceived != null)
             {
                 FriendRequestReceived(this,
                     new FriendRequestEventArgs(msg.Sender, msg.Content));
             }
             break;
         case MessageType.FRIENDSEARCH:
             //好友搜索结果,交由应答处理
             currentResponse = msg;
             break;
         case MessageType.OK:
             currentResponse = msg;
             Debug.WriteLine("response updated {0}", DateTime.Now);
             break;
         case MessageType.ERROR:
             currentResponse = msg;
             Debug.WriteLine("response updated {0}", DateTime.Now);
             break;
         case MessageType.INVALID:
             lock (currentResponse)
             {
                 currentResponse = msg;
                 Debug.WriteLine("response updated {0}", DateTime.Now);
             }
             break;
         case MessageType.CREATECHAT:
             OnNewChatCreated(msg);
             break;
         case MessageType.LEAVECHAT:
             if (UserLeaveChat != null)
             {
                 UserLeaveChat(this, new UserLeaveChatEventArgs(msg.Sender, msg.Content));
             }
             break;
         default:
             break;
     }
 }
Esempio n. 25
0
 //查询聊天信息
 public List<Message> SearchMessage(string keyWord, string userName)
 {
     var selectedMessages = from m in dataContext.DatabaseMessage
                            where (m.Sender == userName || m.Receiver == userName) && (m.Content.Contains(keyWord))
                            orderby m.Time descending
                            select m;
     List<Message> targetMessages = new List<Message>();
     foreach (DatabaseMessage msg in selectedMessages)
     {
         MessageType type = (MessageType)Enum.Parse(typeof(MessageType), msg.Type);
         string sender = msg.Sender;
         string receiver = msg.Receiver;
         string content = msg.Content;
         DateTime time = msg.Time;
         Message newMessage = new Message(type, time, sender, receiver, content);
         targetMessages.Add(newMessage);
     }
     return targetMessages;
 }