TcpServer.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Net;
  6. using System.Net.Sockets;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using DevExpress.XtraEditors;
  10. namespace XzXdDw
  11. {
  12. public class TcpServer
  13. {
  14. private TcpListener listener;
  15. public event Action<byte[]> OnDataReceived;
  16. public void Start(int port, string ip = null)
  17. {
  18. Task.Run(() =>
  19. {
  20. if (string.IsNullOrWhiteSpace(ip))
  21. {
  22. listener = new TcpListener(IPAddress.Any, port);
  23. }
  24. else
  25. {
  26. listener = new TcpListener(IPAddress.Parse(ip), port);
  27. }
  28. listener.Start();
  29. L1:
  30. TcpClient client = null;
  31. try
  32. {
  33. client = listener.AcceptTcpClient();
  34. }
  35. catch (Exception ex)
  36. {
  37. return;
  38. }
  39. while (true)
  40. {
  41. try
  42. {
  43. var stream = client.GetStream();
  44. byte[] lenData = new byte[4];
  45. int readLen = stream.Read(lenData, 0, 4);
  46. if (readLen == 0)
  47. goto L1;
  48. byte[] data = new byte[BitConverter.ToInt32(lenData, 0)];
  49. readLen = stream.Read(data, 0, data.Length);
  50. if (readLen == 0)
  51. goto L1;
  52. OnDataReceived?.Invoke(data);
  53. }
  54. catch (Exception ex)
  55. {
  56. goto L1;
  57. }
  58. }
  59. });
  60. }
  61. public void StopListening()
  62. {
  63. listener?.Stop();
  64. listener = null;
  65. }
  66. /// <summary>
  67. /// TCP发送数据
  68. /// </summary>
  69. /// <param name="serverIP"></param>
  70. /// <param name="port"></param>
  71. /// <param name="strjson"></param>
  72. /// <returns></returns>
  73. public async void SendData(string serverIP, int port, string strjson)
  74. {
  75. await Task.Run(async () =>
  76. {
  77. try
  78. {
  79. using (TcpClient client = new TcpClient())
  80. {
  81. await client.ConnectAsync(serverIP, port);
  82. NetworkStream stream = client.GetStream();
  83. byte[] dataToSend = Encoding.UTF8.GetBytes(strjson);
  84. // 将数据发送到服务器
  85. stream.Write(dataToSend, 0, dataToSend.Length);
  86. }
  87. }
  88. catch (Exception ex)
  89. {
  90. }
  91. });
  92. }
  93. }
  94. }