TcpServer.cs 2.9 KB

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