IPTool.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Text;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. namespace UAS_LabelMachine.PublicMethod
  10. {
  11. class IPTool
  12. {
  13. private Socket socket;
  14. private IPEndPoint serverFullAddr;//完整终端地址
  15. public IPTool(string IP, string Port)
  16. {
  17. try
  18. {
  19. socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  20. serverFullAddr = new IPEndPoint(IPAddress.Parse(IP), int.Parse(Port));//设置IP,端口
  21. socket.ReceiveTimeout = 2000;
  22. socket.Connect(serverFullAddr);
  23. Task.Factory.StartNew(WatchConnecting, TaskCreationOptions.LongRunning);
  24. }
  25. catch (Exception ex)
  26. {
  27. LogManager.DoLog(ex.Message + ex.StackTrace);
  28. }
  29. }
  30. public void SendCommand()
  31. {
  32. try
  33. {
  34. if (!socket.Connected)
  35. {
  36. socket.Close();
  37. socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  38. socket.ReceiveTimeout = 2000;
  39. socket.Connect(serverFullAddr);
  40. }
  41. byte[] receive = new byte[1024 * 10];
  42. int length = socket.Receive(receive);
  43. string str = BaseUtil.ByteToHexadecimalString(receive, length);
  44. Console.WriteLine(str);
  45. }
  46. catch (Exception ex)
  47. {
  48. Console.WriteLine(ex.Message + ex.StackTrace);
  49. }
  50. }
  51. private void WatchConnecting()
  52. {
  53. SendCommand();
  54. }
  55. }
  56. }