using System; using System.Net; using System.Net.Sockets; using System.Threading.Tasks; namespace HDL_ON.DriverLayer { public class Control_TcpClient { //声明IP,端口,和一个用来连接的Socket public string _ip; private TcpClient _tcpClient; //创建一个委托,用来满足其他类调用 public delegate void DelegateMessage(byte[] bytes); public event DelegateMessage OnmessageEvent; /// /// 构造函数 /// public Control_TcpClient(string serverIp) { _ip = serverIp; } //TCP连接 public bool Connect(int _port = 8586) { if (string.IsNullOrEmpty(_ip) || _port == 0) { return false; } _tcpClient = new TcpClient(); try { _tcpClient.Connect(IPAddress.Parse(_ip), _port); Task.Run(new Action(ReceiveMessage));//开启线程,不停接收消息 } catch (Exception e) { Console.WriteLine(e); throw; } return true;//返回连接状态 } /// /// 关闭连接 /// /// public bool Close() { if (_tcpClient == null) return true; _tcpClient.Close(); _tcpClient = null; return true; } /// /// 发送消息 /// /// 需要发送的字节 public void SendMessage(byte[] bytes) { NetworkStream networkStream = _tcpClient.GetStream(); networkStream.Write(bytes, 0, bytes.Length); } //接收消息 public void ReceiveMessage() { NetworkStream networkStream = _tcpClient.GetStream(); while (true) { byte[] buffer = new byte[8]; int size = networkStream.Read(buffer, 0, buffer.Length); OnmessageEvent?.Invoke(buffer); } } } }