/// <summary> /// 查询某个人的数据 /// </summary> /// <param name="queryUserId">查询信息的用户id</param> /// <returns>返回结果串</returns> public UserData QueryUserData(string queryUserId) { // 初始化查询语句 SqlCommand com = new SqlCommand(); com.Connection = con; com.CommandType = CommandType.Text; com.CommandText = "select id, name, gender, age from UserInfo where id = '" + queryUserId + "'"; // 获得查询结果 SqlDataReader ans = com.ExecuteReader(); UserData userData = new UserData(); // 保存信息 if (ans.Read()) userData = new UserData((string)ans[0], (string)ans[1], (string)ans[2], (int)ans[3]); ans.Close(); return userData; }
/// <summary> /// 查询某个用户的好友 /// </summary> /// <param name="userId">用户id</param> /// <returns>好友信息列表</returns> public List<UserData> FindFriendOfSomeone(string userId) { List<UserData> ans = new List<UserData>(); // 初始化查询语句 SqlCommand com = new SqlCommand(); com.Connection = con; com.CommandType = CommandType.Text; com.CommandText = "select id, name, gender, age from Friendship, UserInfo where idA = '" + userId + "' and id = idB"; // 获得查询结果 SqlDataReader rst = com.ExecuteReader(); while(rst.Read()) { UserData userData = new UserData((string)rst[0], (string)rst[1], (string)rst[2], (int)rst[3]); ans.Add(userData); } rst.Close(); SqlCommand comm = new SqlCommand(); comm.Connection = con; comm.CommandType = CommandType.Text; comm.CommandText = "select id, name, gender, age from Friendship, UserInfo where idB = '" + userId + "' and id = idA"; SqlDataReader res = comm.ExecuteReader(); while (res.Read()) { UserData userData = new UserData((string)res[0], (string)res[1], (string)res[2], (int)res[3]); ans.Add(userData); } res.Close(); return ans; }
/// <summary> /// 登录 /// </summary> /// <param name="userId">用户名</param> /// <param name="userPassword">密码</param> /// <param name="userInfo">如果登陆成功返回信息为用户的个人信息</param> /// <returns>返回登录是否成功</returns> public bool Login(string userId, string userPassword, out UserData userData) { userData = new UserData(); // 初始化查询语句 SqlCommand com = new SqlCommand(); com.Connection = con; com.CommandType = CommandType.Text; com.CommandText = "select id, code, name, gender, age from UserInfo where id = '" + userId + "'"; // 获得查询结果 SqlDataReader ans = com.ExecuteReader(); if (ans.Read()) { if (Convert.ToString(ans[1]).Trim().Equals(userPassword)) { userData = new UserData((string)ans[0], (string)ans[2], (string)ans[3], (int)ans[4]); ans.Close(); return true; } else { ans.Close(); return false; } } ans.Close(); return false; }
/// <summary> /// 更新好友列表 /// </summary> /// <param name="flag">增加/删除</param> /// <param name="userData">新上线的用户信息</param> /// <param name="friendlist">新上线用户的好友列表</param> private void UpdateFriendlist(byte flag, UserData userData, List<UserData> friendlist) { // 更新好友列表 FriendlistHandler friendlistHandler = new FriendlistHandler(flag, userData); string sendMsg = JsonConvert.SerializeObject(friendlistHandler); byte[] arrMsg = Encoding.UTF8.GetBytes(sendMsg); byte[] sendArrMsg = new byte[arrMsg.Length + 1]; // 设置标志位,代表登录/注册 sendArrMsg[0] = UPDATE_FRIENDLIST; Buffer.BlockCopy(arrMsg, 0, sendArrMsg, 1, arrMsg.Length); foreach (UserData userdata in friendlist) { // 如果用户在上线用户中 if (dictOnlineUserO.ContainsKey(userdata.userId) == true) { // 找到Ip string userIp = dictOnlineUserO[userdata.userId]; try { // 发送消息 dictSocket[userIp].Send(sendArrMsg); } catch { } } } }
public FriendlistHandler(int t, UserData f) { type = t; friendInfo = f; }
/// <summary> /// 服务端监听客户发来的数据 /// </summary> private void ReceiveMsg(object socketClientPara) { Socket socketClient = socketClientPara as Socket; while (true) { // 定义一个接收消息用的缓冲区 byte[] msgReceiver = new byte[1024 * 1024 * 2]; // 接收消息的长度 int length = -1; try { length = socketClient.Receive(msgReceiver); } catch (SocketException se) { string socketKey = socketClient.RemoteEndPoint.ToString(); Console.WriteLine("【错误】" + socketKey + " 接收消息异常 错误信息:" + se.Message); // 更新客户端显示的在线好友 if (dictOnlineUser.ContainsKey(socketKey)) { string userId = dictOnlineUser[socketKey]; UserData userData = dictDatabaseHandler[socketKey].QueryUserData(userId); List<UserData> listUserData = dictDatabaseHandler[socketKey].FindFriendOfSomeone(userId); UpdateFriendlist(REMOVE_ONLINE_FRIEND, userData, listUserData); // 将出错对象相关联的信息从队列中移除 dictOnlineUserO.Remove(userId); dictOnlineUser.Remove(socketKey); } dictSocket[socketKey].Close(); Thread tmp = dictThread[socketKey]; // 将出错对象相关联的信息从队列中移除 dictSocket.Remove(socketKey); dictThread.Remove(socketKey); dictDatabaseHandler.Remove(socketKey); tmp.Abort(); return; } catch (Exception e) { Console.WriteLine("【错误】" + e.Message); return; } // 判断客户端信息发来的第一位,如果是LOGIN代表是登录请求 if (msgReceiver[0] == LOGIN) { // 查询数据库,判断登录状态 string loginMsg = Encoding.UTF8.GetString(msgReceiver, 1, length-1); LoginHandler loginHandler = (LoginHandler)JsonConvert.DeserializeObject(loginMsg, typeof(LoginHandler)); // 登录 将登录状态返回到flagLogin UserData userData; bool flagLogin = dictDatabaseHandler[socketClient.RemoteEndPoint.ToString()].Login(loginHandler.userId, loginHandler.userPassword, out userData); if (flagLogin == true) { Console.WriteLine("用户 : {0} IP : {1} 已登录...", loginHandler.userId, socketClient.RemoteEndPoint.ToString()); // 如果ip未出现过,则增加数据 if (dictOnlineUser.ContainsKey(socketClient.RemoteEndPoint.ToString()) == false) { dictOnlineUser.Add(socketClient.RemoteEndPoint.ToString(), loginHandler.userId); dictOnlineUserO.Add(loginHandler.userId, socketClient.RemoteEndPoint.ToString()); } // 否则,修改数据 else { dictOnlineUserO.Remove(dictOnlineUser[socketClient.RemoteEndPoint.ToString()]); dictOnlineUser[socketClient.RemoteEndPoint.ToString()] = loginHandler.userId; dictOnlineUserO.Add(loginHandler.userId, socketClient.RemoteEndPoint.ToString()); } // 确认登录信息 Confirm(IS_LOGIN, userData, socketClient.RemoteEndPoint.ToString()); // 更新在线好友列表 List<UserData> listUserData = dictDatabaseHandler[socketClient.RemoteEndPoint.ToString()].FindFriendOfSomeone(userData.userId); UpdateFriendlist(ADD_ONLINE_FRIEND, userData, listUserData); } else { Console.WriteLine("用户 : {0} IP : {1} 试图登录,但用户名或密码错误...", loginHandler.userId, socketClient.RemoteEndPoint.ToString()); // 如果ip未出现过,则增加数据 if (dictOnlineUser.ContainsKey(socketClient.RemoteEndPoint.ToString()) == false) { dictOnlineUser.Add(socketClient.RemoteEndPoint.ToString(), loginHandler.userId); dictOnlineUserO.Add(loginHandler.userId, socketClient.RemoteEndPoint.ToString()); } // 否则,修改数据 else { dictOnlineUserO.Remove(dictOnlineUser[socketClient.RemoteEndPoint.ToString()]); dictOnlineUser[socketClient.RemoteEndPoint.ToString()] = loginHandler.userId; dictOnlineUserO.Add(loginHandler.userId, socketClient.RemoteEndPoint.ToString()); } UserData failedUserData = new UserData(loginHandler.userId, "", "", 0); // 确认登录失败 Confirm(IS_NOT_LOGIN, failedUserData, socketClient.RemoteEndPoint.ToString()); } #region Use For Test /* 功能测试 string loginMsg = Encoding.UTF8.GetString(msgReceiver, 1, length - 1); LoginHandler loginHandler = (LoginHandler)JsonConvert.DeserializeObject(loginMsg, typeof(LoginHandler)); Console.WriteLine("用户 : {0} IP : {1} 已连接...", loginHandler.userName, socketClient.RemoteEndPoint.ToString()); dictOnlineUser.Add(socketClient.RemoteEndPoint.ToString(), loginHandler.userName); dictOnlineUserO.Add(loginHandler.userName, socketClient.RemoteEndPoint.ToString()); 功能测试end */ #endregion } // 注册 else if (msgReceiver[0] == REGISTER) { // 处理注册请求 string registerMsg = Encoding.UTF8.GetString(msgReceiver, 1, length - 1); RegisterHandler registerHandler = (RegisterHandler)JsonConvert.DeserializeObject(registerMsg, typeof(RegisterHandler)); // 获取一个未被注册的ID string userId = dictDatabaseHandler[socketClient.RemoteEndPoint.ToString()].GetNewId(); // 注册新用户 bool flagRegister = dictDatabaseHandler[socketClient.RemoteEndPoint.ToString()].Register(userId, registerHandler.userName, registerHandler.userPassword, registerHandler.userGender, registerHandler.userAge); UserData userData = new UserData(userId, registerHandler.userName, registerHandler.userGender, registerHandler.userAge); if (flagRegister == true) { Console.WriteLine("用户 : {0} IP : {1} 注册成功...", userId, socketClient.RemoteEndPoint.ToString()); // 确认注册信息 Confirm(IS_REGISTER, userData, socketClient.RemoteEndPoint.ToString()); } else { Console.WriteLine("用户 : {0} IP : {1} 注册失败...", userId, socketClient.RemoteEndPoint.ToString()); // 确认登录失败 Confirm(IS_NOT_REGISTER, userData, socketClient.RemoteEndPoint.ToString()); } } // 更新用户信息 else if (msgReceiver[0] == UPDATE_USER_INFO) { // 处理更新信息请求 string updateMsg = Encoding.UTF8.GetString(msgReceiver, 1, length - 1); RegisterHandler registerHandler = (RegisterHandler)JsonConvert.DeserializeObject(updateMsg, typeof(RegisterHandler)); bool flagUpdate = dictDatabaseHandler[socketClient.RemoteEndPoint.ToString()].UpdateUserInfo(registerHandler); UserData userData; userData = new UserData(registerHandler.userId, registerHandler.userName, registerHandler.userGender, registerHandler.userAge); if (flagUpdate == true) { Console.WriteLine("更新用户:{0} IP:{1}信息:\"{2}:{3}:{4}:{5}\"成功", registerHandler.userId, socketClient.RemoteEndPoint.ToString(), registerHandler.userName, registerHandler.userPassword, registerHandler.userGender, registerHandler.userAge); // 确认更新成功 Confirm(IS_UPDATE, userData, socketClient.RemoteEndPoint.ToString()); } else { Console.WriteLine("更新用户:{0} IP:{1}信息:\"{2}:{3}:{4}:{5}\"失败", registerHandler.userId, socketClient.RemoteEndPoint.ToString(), registerHandler.userName, registerHandler.userPassword, registerHandler.userGender, registerHandler.userAge); // 确认更新成功 Confirm(IS_NOT_UPDATE, userData, socketClient.RemoteEndPoint.ToString()); } } // 用户登陆成功,需要初始化已在线的好友列表 else if (msgReceiver[0] == INIT_FRIENDLIST) { // 获取用户id string userIp = socketClient.RemoteEndPoint.ToString(); string userId = dictOnlineUser[userIp]; // 查找用户好友 List<UserData> listUserData = dictDatabaseHandler[userIp].FindFriendOfSomeone(userId); // 初始化好友列表 InitFriendlist(userIp, listUserData); } // 如果在INDIVIDUAL_LOWER_BOUND和INDIVIDUAL_UPPER_BOUND之间,则是发给特定用户的信息或文件 else if (msgReceiver[0] >= INDIVIDUAL_LOWER_BOUND && msgReceiver[0] <= INDIVIDUAL_UPPER_BOUND ) { // 发送消息给特定用户 string sendMsg = Encoding.UTF8.GetString(msgReceiver, 0, length); SendMsgToIndividual(sendMsg); } // 如果在ALL_LOWER_BOUND和ALL_UPPER_BOUND之间,则是发给所有用户的信息或文件 else if (msgReceiver[0] >= ALL_LOWER_BOUND && msgReceiver[0] <= ALL_UPPER_BOUND) { // 发送消息给所有用户 string sendMsg = Encoding.UTF8.GetString(msgReceiver, 0, length); SendMsgToAll(sendMsg); } else if (msgReceiver[0] == ADD_FRIEND || msgReceiver[0] == REMOVE_FRIEND) { string userId = dictOnlineUser[socketClient.RemoteEndPoint.ToString()]; string friendId = Encoding.UTF8.GetString(msgReceiver, 1, length-1); EditFriendOfSomeone(msgReceiver[0], userId, friendId); } // 断开连接 else if (msgReceiver[0] == DISCONNECT) { string socketKey = socketClient.RemoteEndPoint.ToString(); // 更新客户端显示的在线好友 if (dictOnlineUser.ContainsKey(socketKey) == true) { string userId = dictOnlineUser[socketKey]; UserData userData = dictDatabaseHandler[socketKey].QueryUserData(userId); Console.WriteLine("用户 : {0} IP : {1} 已下线...", userId, socketKey); List<UserData> listUserData = dictDatabaseHandler[socketKey].FindFriendOfSomeone(userId); UpdateFriendlist(REMOVE_ONLINE_FRIEND, userData, listUserData); dictOnlineUserO.Remove(userId); dictOnlineUser.Remove(socketKey); } else Console.WriteLine("用户IP : {0} 已下线...", socketKey); dictSocket[socketKey].Close(); Thread tmp = dictThread[socketKey]; // 将下线对象移除列表 dictSocket.Remove(socketKey); dictThread.Remove(socketKey); dictDatabaseHandler.Remove(socketKey); tmp.Abort(); } else //消息传输错误 { string socketKey = socketClient.RemoteEndPoint.ToString(); Console.WriteLine("【错误】" + socketKey + " 接收消息异常"); // 更新客户端显示的在线好友 if (dictOnlineUser.ContainsKey(socketKey) == true) { string userId = dictOnlineUser[socketKey]; UserData userData = dictDatabaseHandler[socketKey].QueryUserData(userId); List<UserData> listUserData = dictDatabaseHandler[socketKey].FindFriendOfSomeone(userId); UpdateFriendlist(REMOVE_ONLINE_FRIEND, userData, listUserData); dictOnlineUserO.Remove(userId); dictOnlineUser.Remove(socketKey); } dictSocket[socketKey].Close(); Thread tmp = dictThread[socketKey]; // 将出错对象相关联的信息从队列中移除 dictSocket.Remove(socketKey); dictThread.Remove(socketKey); dictDatabaseHandler.Remove(socketKey); tmp.Abort(); } } }
/// <summary> /// 确认登录信息 /// </summary> /// <param name="flag">IS_LOGIN或者IS_NOT_LOGIN</param> /// <param name="userData">用户信息</param> private void Confirm(byte flag, UserData userData, string senderIp) { string sendMsg; if (flag == IS_LOGIN || flag == IS_REGISTER || flag == IS_UPDATE) sendMsg = JsonConvert.SerializeObject(userData); else sendMsg = ""; byte[] arrMsg = Encoding.UTF8.GetBytes(sendMsg); byte[] sendArrMsg = new byte[arrMsg.Length + 1]; // 设置标志位,代表登录/注册 sendArrMsg[0] = flag; Buffer.BlockCopy(arrMsg, 0, sendArrMsg, 1, arrMsg.Length); dictSocket[senderIp].Send(sendArrMsg); }