MainForm.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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.TcpClientApp
  12. {
  13. public partial class MainForm : Form
  14. {
  15. TcppClient tcpClient = null;
  16. public MainForm()
  17. {
  18. InitializeComponent();
  19. }
  20. private void BTConnect_Click(object sender, EventArgs e)
  21. {
  22. tcpClient = new TcppClient(TBIP.Text, int.Parse(TBPort.Text),
  23. ReceiveMessage, OnConnect, OnDisconnect);
  24. bool flag = tcpClient.Connect();
  25. if (flag) MessageBox.Show("连接成功");
  26. else MessageBox.Show("连接失败");
  27. }
  28. private void OnConnect(string host)
  29. {
  30. this.Invoke(new Action(() =>
  31. {
  32. TBText.AppendText($"Connect : {host}" + Environment.NewLine);
  33. }));
  34. }
  35. private void OnDisconnect(string host)
  36. {
  37. this.Invoke(new Action(() =>
  38. {
  39. TBText.AppendText($"Disconnect : {host}" + Environment.NewLine);
  40. }));
  41. }
  42. private void ReceiveMessage(string host, TcpDataModel data)
  43. {
  44. this.Invoke(new Action(() =>
  45. {
  46. if (data.Type == 1000)
  47. {
  48. string s = Encoding.UTF8.GetString(data.Data);
  49. int l = s.Length;
  50. TBText.AppendText(host + " : " + s);
  51. TBText.AppendText(Environment.NewLine);
  52. }
  53. }));
  54. }
  55. private void BTSend_Click(object sender, EventArgs e)
  56. {
  57. byte[] sb = Encoding.UTF8.GetBytes(TBMessage.Text);
  58. tcpClient.Write(new TcpDataModel()
  59. {
  60. Type = 1000,
  61. Data = Encoding.UTF8.GetBytes(TBMessage.Text)
  62. });
  63. }
  64. private void BTDisconnect_Click(object sender, EventArgs e)
  65. {
  66. tcpClient?.Disconnect();
  67. }
  68. private void TBText_TextChanged(object sender, EventArgs e)
  69. {
  70. LBTextLength.Text = TBText.TextLength.ToString();
  71. }
  72. private void TBMessage_TextChanged(object sender, EventArgs e)
  73. {
  74. LBMessageLength.Text = TBMessage.TextLength.ToString();
  75. }
  76. private void MainForm_Load(object sender, EventArgs e)
  77. {
  78. }
  79. private void BTClear_Click(object sender, EventArgs e)
  80. {
  81. TBText.Clear();
  82. }
  83. }
  84. }