| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 | 
							- using System;
 
- using System.Collections.Generic;
 
- using System.Linq;
 
- using System.Text;
 
- using System.Net;
 
- using System.Net.Sockets;
 
- using System.Threading;
 
- using System.Threading.Tasks;
 
- namespace XdCxRhDW.App
 
- {
 
-     class TcpServer
 
-     {
 
-         private TcpListener listener;
 
-         public event Action<byte[]> OnDataReceived;
 
-         public void Start(int port, string ip = null)
 
-         {
 
-             Task.Run(() =>
 
-             {
 
-                 if (string.IsNullOrWhiteSpace(ip))
 
-                 {
 
-                     listener = new TcpListener(IPAddress.Any, port);
 
-                 }
 
-                 else
 
-                 {
 
-                     listener = new TcpListener(IPAddress.Parse(ip), port);
 
-                 }
 
-                 listener.Start();
 
-             L1:
 
-                 TcpClient client = null;
 
-                 try
 
-                 {
 
-                      client = listener.AcceptTcpClient();
 
-                 }
 
-                 catch (Exception ex)
 
-                 {
 
-                     return;
 
-                 }
 
-                 while (true)
 
-                 {
 
-                     try
 
-                     {
 
-                         var stream = client.GetStream();
 
-                         byte[] lenData = new byte[4];
 
-                         int readLen = stream.Read(lenData, 0, 4);
 
-                         if (readLen == 0)
 
-                             goto L1;
 
-                         byte[] data = new byte[BitConverter.ToInt32(lenData, 0)];
 
-                         readLen = stream.Read(data, 0, data.Length);
 
-                         if (readLen == 0)
 
-                             goto L1;
 
-                         OnDataReceived?.Invoke(data);
 
-                     }
 
-                     catch (Exception ex)
 
-                     {
 
-                         goto L1;
 
-                     }
 
-                 }
 
-             });
 
-         }
 
-         public void StopListening()
 
-         {
 
-             listener?.Stop();
 
-             listener = null;
 
-         }
 
-     }
 
- }
 
 
  |