ModBusTCPClient.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  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. namespace UAS_PLCDataReader.PublicMethod
  8. {
  9. class ModBusTCPClient
  10. {
  11. private Socket socket;
  12. private IPEndPoint serverFullAddr;//完整终端地址
  13. private bool isOpen = false;
  14. private bool receiveData;
  15. private Dictionary<string, string> returnvalue = new Dictionary<string, string>();
  16. public bool IsOpen
  17. {
  18. get
  19. {
  20. return isOpen;
  21. }
  22. set
  23. {
  24. isOpen = value;
  25. }
  26. }
  27. public string IP
  28. {
  29. get
  30. {
  31. return iP;
  32. }
  33. set
  34. {
  35. iP = value;
  36. }
  37. }
  38. public string Port
  39. {
  40. get
  41. {
  42. return port;
  43. }
  44. set
  45. {
  46. port = value;
  47. }
  48. }
  49. public bool ReceiveData
  50. {
  51. get
  52. {
  53. return receiveData;
  54. }
  55. set
  56. {
  57. receiveData = value;
  58. }
  59. }
  60. public Dictionary<string, string> Returnvalue
  61. {
  62. get
  63. {
  64. return returnvalue;
  65. }
  66. set
  67. {
  68. returnvalue = value;
  69. }
  70. }
  71. private string iP;
  72. private string port;
  73. public ModBusTCPClient(string IP, int Port)
  74. {
  75. socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  76. serverFullAddr = new IPEndPoint(IPAddress.Parse(IP), Port);//设置IP,端口
  77. try
  78. {
  79. socket.Connect(serverFullAddr);
  80. }
  81. catch (Exception)
  82. {
  83. }
  84. }
  85. public void Send(string Command)
  86. {
  87. Command = Command.Replace(" ", "");
  88. byte[] arr = new byte[Command.Length / 2];
  89. for (int i = 0; i < Command.Length / 2; i++)
  90. {
  91. arr[i] = (byte)Convert.ToInt32(Command.Substring(i * 2, 2), 16);
  92. }
  93. socket.Send(arr);
  94. byte[] receive = new byte[1024 * 1024];
  95. int length = socket.Receive(receive);
  96. Console.WriteLine(BaseUtil.ByteToHexadecimalString(receive, length));
  97. if (!returnvalue.ContainsKey(socket.RemoteEndPoint.ToString()))
  98. {
  99. returnvalue.Add(socket.RemoteEndPoint.ToString(), BaseUtil.ByteToHexadecimalString(receive, length));
  100. }
  101. }
  102. }
  103. }