private void buttonRegister_Click(object sender, EventArgs e) { try { textBoxUserName.Text = textBoxUserName.Text.Trim(); if (textBoxUserName.Text == "") { throw new Exception("请输入用户名"); } if (textBoxPassword.Text == "") { throw new Exception("请输入密码"); } if (textBoxVerbPasswrod.Text == "") { throw new Exception("请输入确认密码"); } if (textBoxPassword.Text != textBoxVerbPasswrod.Text) { throw new Exception("两次输入密码不一样"); } JObject json = JObject.Parse("{\"action\":\"register\",\"username\":\"\",\"password\":\"\"}"); json["username"] = textBoxUserName.Text; json["password"] = textBoxPassword.Text; NetworkStreamProcessing.WriteBase64BytesEncodedJObjectToNetworkStream(Client.Stream, json); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } }
/// <summary> /// 显示登陆框并返回用户 /// </summary> /// <returns></returns> public new User ShowDialog() { new Thread(() => { UdpClient client; try { client = new UdpClient(new IPEndPoint(IPAddress.Any, 16999)); } catch { return; } client.EnableBroadcast = true; IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 0); byte[] receive; try { receive = client.Receive(ref ipep); } catch { try { client.Close(); } catch { } return; } try { client.Close(); } catch { } Newtonsoft.Json.Linq.JObject json; try { json = NetworkStreamProcessing.GetJObjectFromBase64Bytes(receive); } catch { return; } IPAddress ipaddr = null; int port = (int)json["port"]; foreach (IPAddress tmp in Dns.GetHostAddresses((string)json["hostname"])) { try { TcpClient tmp1 = new TcpClient(); tmp1.Connect(tmp, port); tmp1.Close(); ipaddr = tmp; break; } catch { } } this.Invoke(new Action(() => { try { serverSettingIpAddressTextBox.Text = ipaddr.ToString(); serverSettingPortTextBox.Text = port.ToString(); } catch { } })); }) { IsBackground = true }.Start(); if (base.ShowDialog() == DialogResult.OK) { return(user); } else { return(null); } }
private void 发起会话ToolStripMenuItem_Click(object sender, EventArgs e) { if (onlineUserTreeView.SelectedNode != null) { if (onlineUserTreeView.SelectedNode.Tag is User) { if (((User)onlineUserTreeView.SelectedNode.Tag).Id == Client.User.Id) { return; } PrivateChatSession tmp; try { tmp = new PrivateChatSession(this, (User)onlineUserTreeView.SelectedNode.Tag, Client.User, (from, to, msg) => { Chat.SendChatToStream(from, to, msg, Client.Stream); }, (filename, to) => { int hash; try { hash = File.ReadAllBytes(filename).GetHashCode(); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } try { var tmp1 = Client.SendFilePool[hash]; MessageBox.Show("正在发送此文件"); return; } catch { Client.SendFilePool.Add(hash, filename); Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.Linq.JObject.Parse($"{{\"action\":\"file\",\"hash\":{hash},\"filename\":\"\",\"toUser\":{to}}}"); json["filename"] = filename.Substring(filename.LastIndexOf('\\') + 1); NetworkStreamProcessing.WriteBase64BytesEncodedJObjectToNetworkStream(Client.Stream, json); } }); } catch { return; } Client.ReceiveChat += tmp.ReceiveChat; Client.UserLogout += tmp.UserLogout; tmp.FormClosed += (a, b) => { Client.ReceiveChat -= tmp.ReceiveChat; Client.UserLogout -= tmp.UserLogout; }; tmp.Show(); } } }
/// <summary> /// 登陆 /// </summary> /// <param name="username"></param> /// <param name="password"></param> public static User Login(string username, string password) { if (IsLogined) { throw new Exception("已经登陆了"); } JObject tmp = JObject.Parse("{\"action\":\"login\",\"username\":\"\",\"password\":\"\"}"); tmp["username"] = username; tmp["password"] = password; NetworkStreamProcessing.WriteBase64BytesEncodedJObjectToNetworkStream(client.GetStream(), tmp); while (User == null) { if (lastError == "login") { Exception e = new Exception(lastError); lastError = null; throw e; } } NetworkStreamProcessing.WriteBase64BytesEncodedJObjectToNetworkStream(client.GetStream(), JObject.Parse("{\"action\":\"getAllUser\"}")); return(User); }
/// <summary> /// 处理客户端的方法 /// </summary> public static void ProcessTcpClient() { using (NetworkStream ns = client.GetStream()) { string receiveError = ""; while (client.Connected) { JObject json; try { json = NetworkStreamProcessing.GetJObjectFromBase64Bytes(NetworkStreamProcessing.ReadDataFromNetworkStream(ns)); } catch (Exception e) { receiveError = e.Message; break; } if ((string)json["application"] != "LNC") { client.Close(); } try { if ((bool)json["error"] == true) { #region error string action = (string)json["action"]; string errorMessage = (string)json["errorMessage"]; string errorType = (string)json["errorType"]; new Thread(() => { System.Windows.Forms.MessageBox.Show($"详细信息如下:\n\n执行的动作: {action}\n\n错误类型:{errorType}\n\n错误信息:\n{errorMessage}", "错误", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); lastError = (string)json["action"]; }) { IsBackground = true }.Start(); #endregion } else { switch ((string)json["action"]) { #region login case "login": User = User.GetUserFromJObject((JObject)json["user"]); break; #endregion #region changeUserInfo case "changeUserInfo": User tmp04 = User.GetUserFromJObject((JObject)json["user"]); if (tmp04.Id == User.Id) { User.ChangeInformation(tmp04); } else { LoginedUser[tmp04.Id].ChangeInformation(tmp04); } Program.mainForm.Invoke(new Action(() => { UserInformationChanged?.Invoke(null, tmp04); })); break; #endregion #region chat case "chat": Chat tmp = Chat.GetChatFromJObject(JObject.Parse(json["chat"].ToString())); try { tmp.User = LoginedUser[tmp.UserId]; } catch { break; } if (tmp.ToUserId == -1) { _chatMessages.Add(tmp); } else { LoginedUser[tmp.UserId].Messages.Add(tmp); } Program.mainForm.Invoke(new Action(() => { ReceiveChat?.Invoke(null, tmp); })); break; #endregion #region getAllUser case "getAllUser": List <User> tmp1 = new List <User>(); foreach (JToken t in JArray.Parse(json["users"].ToString())) { User u = User.GetUserFromJObject(JObject.Parse(t.ToString())); LoginedUser.Add(u.Id, u); tmp1.Add(u); } Program.mainForm.Invoke(new Action(() => { ReceiveOnlineUser?.Invoke(null, tmp1.ToArray()); })); break; #endregion #region login2 case "login2": User user = User.GetUserFromJObject(JObject.Parse(json["user"].ToString())); LoginedUser.Add(user.Id, user); Program.mainForm.Invoke(new Action(() => { UserLogin?.Invoke(null, user); })); break; #endregion #region logout case "logout": User user2 = User.GetUserFromJObject(JObject.Parse(json["user"].ToString())); var tmp3 = LoginedUser[user2.Id]; LoginedUser.Remove(user2.Id); Program.mainForm.Invoke(new Action(() => { UserLogout?.Invoke(null, tmp3); })); break; #endregion #region file case "file": string filename = (string)json["filename"]; int hash = (int)json["hash"]; int toUser = (int)json["toUser"]; int fromUser = (int)json["fromUser"]; int port = (int)json["port"]; new Thread(() => { TcpClient tmp0 = new TcpClient(); tmp0.Connect(new IPEndPoint(serverIP, port)); //Thread.Sleep(1000); JObject json1 = JObject.Parse("{\"type\":\"\"}"); if (fromUser == User.Id) { json["type"] = "send"; } else { json["type"] = "receive"; } NetworkStreamProcessing.WriteBase64BytesEncodedJObjectToNetworkStream(tmp0.GetStream(), json); JObject json2 = NetworkStreamProcessing.GetJObjectFromBase64Bytes(NetworkStreamProcessing.ReadDataFromNetworkStream(tmp0.GetStream())); if ((int)json2["hash"] != hash) { return; } NetworkStream ns0 = tmp0.GetStream(); if (fromUser == User.Id) { FileStream fs; try { fs = new FileStream(SendFilePool[hash], FileMode.Open); } catch { if (tmp0.Connected) { tmp0.Close(); } return; } while (fs.Position < fs.Length) { byte[] buffer = new byte[8192]; try { int s = fs.Read(buffer, 0, 8192); ns0.Write(buffer, 0, s); } catch { if (tmp0.Connected) { tmp0.Close(); } fs.Dispose(); return; } } try { fs.Close(); } catch { } } else { if (!Directory.Exists("ReceiveFiles")) { Directory.CreateDirectory("ReceiveFiles"); } FileStream fs; try { fs = new FileStream(@"ReceiveFiles\" + filename, FileMode.CreateNew); } catch { if (tmp0.Connected) { tmp0.Close(); } return; } while (tmp0.Connected) { try { byte[] buffer = NetworkStreamProcessing.ReadDataFromNetworkStream(ns0); if (buffer.Length == 0) { tmp0.Close(); } fs.Write(buffer, 0, buffer.Length); } catch { if (tmp0.Connected) { tmp0.Close(); } fs.Dispose(); } } try { fs.Close(); } catch { } if (tmp0.Connected) { tmp0.Close(); } if (File.ReadAllBytes(@"ReceiveFiles\" + filename).GetHashCode() != hash) { System.Windows.Forms.MessageBox.Show($"\"{filename}\" 文件已损坏!"); } } }) { IsBackground = true }.Start(); break; #endregion #region register case "register": if ((string)json["status"] == "success") { Registered?.Invoke(null, EventArgs.Empty); } break; #endregion #region getNotVerifiedUsers case "getNotVerifiedUsers": List <User> tmp01 = new List <User>(); foreach (JObject t in JArray.Parse(json["users"].ToString())) { tmp01.Add(User.GetUserFromJObject(t)); } User[] tmp03 = tmp01.ToArray(); new Thread(() => { VerifyUserForm tmp02 = new VerifyUserForm(null, tmp03); tmp02.AcceptUser += (a, b) => { b.ChangeInformationAndPushToServer(b.Name, b.Age, b.Birth, b.Telephone, b.Pay, b.Unit, b.Number, 1, b.Banned, Client.Stream); }; tmp02.DenyUser += (a, b) => { b.ChangeInformationAndPushToServer(b.Name, b.Age, b.Birth, b.Telephone, b.Pay, b.Unit, b.Number, -1, b.Banned, Client.Stream); }; tmp02.InformationOpened += (a, b) => { new Thread(() => { try { new PersonalInfomation(b, User).ShowDialog(); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } }).Start(); }; tmp02.ShowDialog(); }) { IsBackground = true }.Start(); break; #endregion #region getAllUserFromDatabase case "getAllUserFromDatabase": List <User> tmp001 = new List <User>(); foreach (JObject t in JArray.Parse(json["users"].ToString())) { tmp001.Add(User.GetUserFromJObject(t)); } User[] tmp003 = tmp001.ToArray(); new Thread(() => { ChangeAllUsersInformationForm cauif = null; (cauif = new ChangeAllUsersInformationForm(User, tmp003, (a) => { try { new PersonalInfomation(a, User).ShowDialog(); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } cauif.Refresh(); })).ShowDialog(); }) { IsBackground = true }.Start(); break; #endregion } } } catch { } } if (receiveError != "") { System.Windows.Forms.MessageBox.Show($"与服务器断开连接!\n\n详细信息:{receiveError}"); } else { System.Windows.Forms.MessageBox.Show($"与服务器断开连接!"); } Disconnected?.Invoke(null, EventArgs.Empty); } }
/// <summary> /// 处理客户端 /// </summary> /// <param name="obj">客户端 (TcpClient)</param> public static void ProcessTcpClient(object obj) { TcpClient client = obj as TcpClient; if (client == null) { return; } using (NetworkStream ns = client.GetStream()) { User user = null; while (client.Connected) { try { JObject json = NetworkStreamProcessing.GetJObjectFromBase64Bytes(NetworkStreamProcessing.ReadDataFromNetworkStream(ns)); if ((string)json["application"] != "LNC") { client.Close(); } try { if (user == null) { switch ((string)json["action"]) { #region login case "login": if (User.Name == (string)json["username"]) { throw new Exception("该用户已经登陆了"); } foreach (KeyValuePair <int, KeyValuePair <User, TcpClient> > tmp1 in LoginedUser) { if (tmp1.Value.Key.UserName == (string)json["username"]) { throw new Exception("该用户已经登陆了"); } } if (!User.CanLogin((string)json["username"], (string)json["password"])) { throw new Exception("账号或密码错误"); } else { user = User.GetUserByUserNameFromDatabase((string)json["username"]); if (user.Level == 0) { throw new Exception("你还没有审核"); } if (user.Level == -1) { throw new Exception("用户审核未通过"); } JObject tmp = JObject.Parse("{\"action\":\"login\",\"result\":\"success\",\"user\":null}"); tmp["user"] = user.ToJObject(); NetworkStreamProcessing.WriteBase64BytesEncodedJObjectToNetworkStream(ns, tmp); JObject json3 = JObject.Parse("{\"action\":\"login2\",\"user\":null}"); json3["user"] = user.ToJObject(); foreach (KeyValuePair <int, KeyValuePair <User, TcpClient> > kvp in LoginedUser) { new Thread(() => { try { NetworkStreamProcessing.WriteBase64BytesEncodedJObjectToNetworkStream(kvp.Value.Value.GetStream(), json3); } catch { } }) { IsBackground = true } } .Start(); LoginedUser.Add(user.Id, new KeyValuePair <User, TcpClient>(user, client)); Program.mainForm.Invoke(new Action(() => { UserLogin?.Invoke(null, user); })); } break; #endregion #region register case "register": string tmp01 = (string)json["username"]; string tmp02 = (string)json["password"]; User.RegisterAndPushToDatabase(tmp01, tmp02); json.Add("result", "success"); json.Remove("username"); json.Remove("password"); NetworkStreamProcessing.WriteBase64BytesEncodedJObjectToNetworkStream(ns, json); break;
private void userInformationButton_Click(object sender, EventArgs e) { NetworkStreamProcessing.WriteBase64BytesEncodedJObjectToNetworkStream(Client.Stream, Newtonsoft.Json.Linq.JObject.Parse("{\"action\":\"getAllUserFromDatabase\"}")); }
private void verifyUserButton_Click(object sender, EventArgs e) { NetworkStreamProcessing.WriteBase64BytesEncodedJObjectToNetworkStream(Client.Stream, Newtonsoft.Json.Linq.JObject.Parse("{\"action\":\"getNotVerifiedUsers\"}")); }
private void Client_ReceiveChat(object sender, Chat e) { if (e.ToUserId == -1) { chatRichTextBox.Invoke(new Action(() => { chatRichTextBox.SelectionLength = 0; chatRichTextBox.ReadOnly = false; chatRichTextBox.SelectionStart = chatRichTextBox.Text.Length; chatRichTextBox.SelectionBackColor = Color.Empty; chatRichTextBox.SelectionIndent = 0; chatRichTextBox.SelectionHangingIndent = 0; chatRichTextBox.SelectionFont = new Font("微软雅黑", 8); chatRichTextBox.AppendText("\n"); if (e.UserId == Client.User.Id) { chatRichTextBox.SelectionColor = Color.DarkGreen; } else { chatRichTextBox.SelectionColor = Color.Blue; } chatRichTextBox.AppendText($"{e.User.Name} ({e.User.UserName}) {DateTime.Now.ToString("yyyy/MM/dd H:mm:ss")}\n"); chatRichTextBox.SelectionColor = Color.Black; chatRichTextBox.SelectionHangingIndent = 20; chatRichTextBox.SelectionFont = new Font("微软雅黑", 10); chatRichTextBox.AppendText(" "); chatRichTextBox.SelectionStart--; chatRichTextBox.SelectionLength = 1; chatRichTextBox.SelectedRtf = e.Message; chatRichTextBox.ReadOnly = true; chatRichTextBox.ScrollToCaret(); })); } else if (e.ToUserId == Client.User.Id) { foreach (Form frm in Application.OpenForms) { if (frm != this) { if (frm is PrivateChatSession) { if (((PrivateChatSession)frm).ToUser.Id == e.User.Id) { frm.Focus(); return; } } } } PrivateChatSession tmp; try { tmp = new PrivateChatSession(this, e.User, Client.User, (from, to, msg) => { Chat.SendChatToStream(from, to, msg, Client.Stream); }, (filename, to) => { int hash; try { hash = File.ReadAllBytes(filename).GetHashCode(); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } try { var tmp1 = Client.SendFilePool[hash]; MessageBox.Show("正在发送此文件"); return; } catch { Client.SendFilePool.Add(hash, filename); Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.Linq.JObject.Parse($"{{\"action\":\"file\",\"hash\":{hash},\"filename\":\"\",\"toUser\":{to}}}"); json["filename"] = filename.Substring(filename.LastIndexOf('\\') + 1); NetworkStreamProcessing.WriteBase64BytesEncodedJObjectToNetworkStream(Client.Stream, json); } }); } catch { return; } Client.ReceiveChat += tmp.ReceiveChat; Client.UserLogout += tmp.UserLogout; tmp.FormClosed += (a, b) => { Client.ReceiveChat -= tmp.ReceiveChat; Client.UserLogout -= tmp.UserLogout; }; tmp.Show(); } }