using System; using System.Net; using System.Net.Sockets; using System.Text; namespace CellStepSender { public class TcpClientTool3 { private string _ip; private int _port; private bool _isConnected = false; // 是否连接 private Socket _clientSocket; // 套接字 public event EventHandler ExecuteMessageChanged; public TcpClientTool3(string ip, int port) { this._ip = ip; this._port = port; } public void Connect() { try { _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress ipaddress = IPAddress.Parse(this._ip); IPEndPoint endpoint = new IPEndPoint(ipaddress, _port); _clientSocket.Connect(endpoint); _isConnected = true; } catch (Exception ex) { _clientSocket.Dispose(); _isConnected = false; throw ex; } } public void Disconnect() { _clientSocket.Dispose(); } public void Send(string data) { byte[] arrClientSendMsg = Encoding.UTF8.GetBytes(data); lock (this) { _clientSocket.Send(arrClientSendMsg); } } public bool SendStep( string ip, int port, int ovenIndex, int cellIndex, string step, string value, string limitUp, string limitDown, string unit, string result, string updateTime, out string errorMsg) { errorMsg = null; try { if (!_isConnected) { errorMsg = "Not Connected"; return false; } string msg = $"{ovenIndex};{cellIndex};{step},{value},{limitUp},{limitDown},{unit},{result},{updateTime}\n"; Send(msg); return true; } catch (Exception ex) { errorMsg = ex.Message; return false; } } } }