MainForm.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. using Azylee.YeahWeb.SocketUtils.TcpUtils;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.Data;
  6. using System.Drawing;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using System.Windows.Forms;
  11. namespace Test.TcpServerApp
  12. {
  13. public partial class MainForm : Form
  14. {
  15. TcppServer tcpServer = null;
  16. public MainForm()
  17. {
  18. InitializeComponent();
  19. }
  20. private void Form1_Load(object sender, EventArgs e)
  21. {
  22. }
  23. private void TBText_TextChanged(object sender, EventArgs e)
  24. {
  25. LBTextLength.Text = TBText.TextLength.ToString();
  26. }
  27. private void BTStart_Click(object sender, EventArgs e)
  28. {
  29. TBText.AppendText("正在监听:" + TBPort.Text + "\n");
  30. tcpServer = new TcppServer(int.Parse(TBPort.Text),
  31. ReceiveMessage, OnConnect, OnDisconnect);
  32. tcpServer?.Start();
  33. }
  34. private void BTStop_Click(object sender, EventArgs e)
  35. {
  36. tcpServer?.Stop();
  37. CBHost.Items.Clear();
  38. }
  39. private void BTSend_Click(object sender, EventArgs e)
  40. {
  41. try
  42. {
  43. string host = CBHost.SelectedItem.ToString();
  44. tcpServer.Write(host, new TcpDataModel()
  45. {
  46. Type = 1000,
  47. Data = Encoding.UTF8.GetBytes(TBMessage.Text)
  48. });
  49. }
  50. catch { }
  51. }
  52. #region Tcp 委托方法
  53. private void OnConnect(string host)
  54. {
  55. this.Invoke(new Action(() =>
  56. {
  57. TBText.AppendText($"Connect : {host}" + Environment.NewLine);
  58. CBHost.Items.Add(host);
  59. LBConnect.Text = tcpServer.ClientsCount().ToString();
  60. }));
  61. }
  62. private void OnDisconnect(string host)
  63. {
  64. this.Invoke(new Action(() =>
  65. {
  66. TBText.AppendText($"Disconnect : {host}" + Environment.NewLine);
  67. CBHost.Items.Remove(host);
  68. }));
  69. }
  70. private void ReceiveMessage(string host, TcpDataModel data)
  71. {
  72. this.Invoke(new Action(() =>
  73. {
  74. if (data.Type == 1000)
  75. {
  76. string s = Encoding.UTF8.GetString(data.Data);
  77. int l = s.Length;
  78. TBText.AppendText(host + " : " + s);
  79. TBText.AppendText(Environment.NewLine);
  80. }
  81. }));
  82. }
  83. #endregion
  84. private void TBMessage_TextChanged(object sender, EventArgs e)
  85. {
  86. LBMessageLength.Text = TBMessage.TextLength.ToString();
  87. }
  88. private void BTClear_Click(object sender, EventArgs e)
  89. {
  90. TBText.Clear();
  91. }
  92. }
  93. }