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 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; } } }