TcpServer.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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
  10. {
  11. 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. }
  66. }