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; using DevExpress.XtraEditors; namespace XzXdDw { public 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; } /// /// TCP发送数据 /// /// /// /// /// public async void SendData(string serverIP, int port, string strjson) { await Task.Run(async () => { try { using (TcpClient client = new TcpClient()) { await client.ConnectAsync(serverIP, port); NetworkStream stream = client.GetStream(); byte[] dataToSend = Encoding.UTF8.GetBytes(strjson); // 将数据发送到服务器 stream.Write(dataToSend, 0, dataToSend.Length); } } catch (Exception ex) { } }); } } }