using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; namespace UAS_LabelMachine.PublicMethod { class IPTool { private Socket socket; private IPEndPoint serverFullAddr;//完整终端地址 public IPTool(string IP, string Port) { try { socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); serverFullAddr = new IPEndPoint(IPAddress.Parse(IP), int.Parse(Port));//设置IP,端口 socket.ReceiveTimeout = 2000; socket.Connect(serverFullAddr); Task.Factory.StartNew(WatchConnecting, TaskCreationOptions.LongRunning); } catch (Exception ex) { LogManager.DoLog(ex.Message + ex.StackTrace); } } public void SendCommand() { try { if (!socket.Connected) { socket.Close(); socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.ReceiveTimeout = 2000; socket.Connect(serverFullAddr); } byte[] receive = new byte[1024 * 10]; int length = socket.Receive(receive); string str = BaseUtil.ByteToHexadecimalString(receive, length); Console.WriteLine(str); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); } } private void WatchConnecting() { SendCommand(); } } }