GetDataFromDevice.cs 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using System.Threading;
  5. using System.Windows.Forms;
  6. using UAS_MES_NEW.DataOperate;
  7. using UAS_MES_NEW.Entity;
  8. namespace UAS_MES_NEW.PublicMethod
  9. {
  10. class GetDataFromDevice
  11. {
  12. DataHelper dh = SystemInf.dh;
  13. public GetDataFromDevice()
  14. {
  15. }
  16. private bool isOpen = false;
  17. Thread threadWatch = null; //负责监听客户端的线程
  18. Socket socketWatch = null; //负责监听客户端的套接字
  19. Socket socConnection;
  20. public bool IsOpen
  21. {
  22. get
  23. {
  24. return isOpen;
  25. }
  26. set
  27. {
  28. isOpen = value;
  29. }
  30. }
  31. public string IP
  32. {
  33. get
  34. {
  35. return iP;
  36. }
  37. set
  38. {
  39. iP = value;
  40. }
  41. }
  42. public string Port
  43. {
  44. get
  45. {
  46. return port;
  47. }
  48. set
  49. {
  50. port = value;
  51. }
  52. }
  53. private string iP;
  54. private string port;
  55. public bool Open()
  56. {
  57. try
  58. {
  59. //定义一个套接字用于监听客户端发来的信息 包含3个参数(IP4寻址协议,流式连接,TCP协议)
  60. socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  61. //服务端发送信息 需要1个IP地址和端口号
  62. IPAddress ipaddress = IPAddress.Parse(iP);
  63. //将IP地址和端口号绑定到网络节点endpoint上
  64. IPEndPoint endpoint = new IPEndPoint(ipaddress, int.Parse(port));
  65. //监听绑定的网络节点
  66. socketWatch.Bind(endpoint);
  67. //将套接字的监听队列长度限制为20
  68. socketWatch.Listen(20);
  69. //创建一个监听线程
  70. threadWatch = new Thread(WatchConnecting);
  71. //将窗体线程设置为与后台同步
  72. threadWatch.IsBackground = true;
  73. //启动线程
  74. threadWatch.Start();
  75. isOpen = true;
  76. return true;
  77. }
  78. catch (Exception e)
  79. {
  80. MessageBox.Show(e.Message);
  81. return false;
  82. }
  83. }
  84. private void WatchConnecting()
  85. {
  86. socConnection = socketWatch.Accept();
  87. while (true) //持续不断监听客户端发来的请求
  88. {
  89. byte[] data = new byte[1024];
  90. socConnection.Receive(data);
  91. //获取发送客户端的IP地址
  92. string clientIP = socConnection.RemoteEndPoint.ToString();
  93. int length = data[5];
  94. byte[] datashow = new byte[length + 6];
  95. for (int i = 0; i <= length + 5; i++)
  96. {
  97. datashow[i] = data[i];
  98. }
  99. string stringdata = BitConverter.ToString(datashow);//把数组转换成16进制字符串
  100. }
  101. }
  102. public void Close()
  103. {
  104. threadWatch.Abort();
  105. socketWatch.Close();
  106. isOpen = false;
  107. }
  108. public void SendOrder(string Code)
  109. {
  110. //socConnection.Send(null);
  111. }
  112. }
  113. }