ModeBusTCPServer.cs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. using System.Text;
  6. using System.Threading;
  7. using System.Windows.Forms;
  8. namespace UAS_DeviceMonitor.PublicMethod
  9. {
  10. class ModeBusTCPServer
  11. {
  12. private bool isOpen = false;
  13. Thread threadWatch = null; //负责监听客户端的线程
  14. Socket socketWatch = null; //负责监听客户端的套接字
  15. public bool IsOpen
  16. {
  17. get
  18. {
  19. return isOpen;
  20. }
  21. set
  22. {
  23. isOpen = value;
  24. }
  25. }
  26. public string IP
  27. {
  28. get
  29. {
  30. return iP;
  31. }
  32. set
  33. {
  34. iP = value;
  35. }
  36. }
  37. public string Port
  38. {
  39. get
  40. {
  41. return port;
  42. }
  43. set
  44. {
  45. port = value;
  46. }
  47. }
  48. private string iP;
  49. private string port;
  50. public List<Socket> list = new List<Socket>();
  51. public ModeBusTCPServer()
  52. {
  53. }
  54. public bool Open()
  55. {
  56. try
  57. {
  58. IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());
  59. for (int i = 0; i < IpEntry.AddressList.Length; i++)
  60. {
  61. if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
  62. iP = IpEntry.AddressList[i].ToString();
  63. }
  64. Console.WriteLine(iP);
  65. //定义一个套接字用于监听客户端发来的信息 包含3个参数(IP4寻址协议,流式连接,TCP协议)
  66. socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  67. //服务端发送信息 需要1个IP地址和端口号
  68. IPAddress ipaddress = IPAddress.Parse(iP);
  69. //将IP地址和端口号绑定到网络节点endpoint上
  70. IPEndPoint endpoint = new IPEndPoint(ipaddress, 8090);
  71. //监听绑定的网络节点
  72. socketWatch.Bind(endpoint);
  73. //将套接字的监听队列长度限制为20
  74. socketWatch.Listen(20);
  75. //创建一个监听线程
  76. threadWatch = new Thread(WatchConnecting);
  77. //将窗体线程设置为与后台同步
  78. threadWatch.IsBackground = true;
  79. //启动线程
  80. threadWatch.Start();
  81. isOpen = true;
  82. return true;
  83. }
  84. catch (Exception e)
  85. {
  86. MessageBox.Show(e.Message);
  87. return false;
  88. }
  89. }
  90. public void Send(string IPAddress, string EnCoding, string Command)
  91. {
  92. foreach (Socket item in list)
  93. {
  94. if (item != null)
  95. {
  96. if (item.RemoteEndPoint != null)
  97. {
  98. if (item.RemoteEndPoint.ToString() == IPAddress)
  99. {
  100. switch (EnCoding)
  101. {
  102. case "UTF-8":
  103. item.Send(Encoding.UTF8.GetBytes(Command));
  104. break;
  105. case "ASCII":
  106. byte[] array = Encoding.ASCII.GetBytes(Command);
  107. string str = null;
  108. for (int i = 0; i < array.Length; i++)
  109. {
  110. int asciicode = (int)(array[i]);
  111. str += Convert.ToString(asciicode) + " ";
  112. }
  113. item.Send(Encoding.ASCII.GetBytes(str));
  114. break;
  115. case "Hexadecimal":
  116. char[] values = Command.ToCharArray();
  117. string strH = null;
  118. foreach (char letter in values)
  119. {
  120. // Get the integral value of the character.
  121. int value = Convert.ToInt32(letter);
  122. // Convert the decimal value to a hexadecimal value in string form.
  123. string hexOutput = String.Format("{0:X}", value);
  124. strH += hexOutput + " ";
  125. }
  126. item.Send(Encoding.UTF8.GetBytes(strH));
  127. break;
  128. }
  129. }
  130. }
  131. else
  132. {
  133. if (list.Count > 0)
  134. {
  135. if (IPAddress == "")
  136. IPAddress = list[0].RemoteEndPoint.ToString();
  137. }
  138. else
  139. IPAddress = "";
  140. if (list.Contains(item))
  141. {
  142. list.Remove(item);
  143. }
  144. //关闭之前accept出来的和客户端进行通信的套接字
  145. item.Close();
  146. }
  147. }
  148. }
  149. }
  150. private void WatchConnecting()
  151. {
  152. Socket connection = null;
  153. while (true) //持续不断监听客户端发来的请求
  154. {
  155. try
  156. {
  157. connection = socketWatch.Accept();
  158. }
  159. catch (Exception)
  160. {
  161. break;
  162. }
  163. //获取客户端的IP和端口号
  164. IPAddress clientIP = (connection.RemoteEndPoint as IPEndPoint).Address;
  165. int clientPort = (connection.RemoteEndPoint as IPEndPoint).Port;
  166. //让客户显示"连接成功的"的信息
  167. string sendmsg = "Connect Success!" + "LocalIP:" + clientIP + ",LocalPort" + clientPort.ToString();
  168. byte[] arrSendMsg = Encoding.UTF8.GetBytes(sendmsg);
  169. connection.Send(arrSendMsg);
  170. //客户端网络结点号
  171. string remoteEndPoint = connection.RemoteEndPoint.ToString();
  172. //显示与客户端连接情况
  173. IPEndPoint netpoint = connection.RemoteEndPoint as IPEndPoint;
  174. //创建一个通信线程
  175. ParameterizedThreadStart pts = new ParameterizedThreadStart(recv);
  176. Thread thread = new Thread(pts);
  177. //设置为后台线程,随着主线程退出而退出
  178. thread.IsBackground = true;
  179. //启动线程
  180. thread.Start(connection);
  181. //创建一个通信线程
  182. //ParameterizedThreadStart sed = new ParameterizedThreadStart(sends);
  183. //Thread threadsed = new Thread(sed);
  184. //设置为后台线程,随着主线程退出而退出
  185. //threadsed.IsBackground = true;
  186. //启动线程
  187. //threadsed.Start(connection);
  188. list.Add(connection);
  189. }
  190. }
  191. void recv(object socketclientpara)
  192. {
  193. Socket socketServer = socketclientpara as Socket;
  194. while (true)
  195. {
  196. //创建一个内存缓冲区,其大小为1024*1024字节 即1M
  197. byte[] arrServerRecMsg = new byte[1024 * 1024];
  198. //将接收到的信息存入到内存缓冲区,并返回其字节数组的长度
  199. try
  200. {
  201. int length = socketServer.Receive(arrServerRecMsg);
  202. if (length == 0)
  203. {
  204. break;
  205. }
  206. //将机器接受到的字节数组转换为人可以读懂的字符串
  207. string strSRecMsg = Encoding.UTF8.GetString(arrServerRecMsg, 0, length);
  208. //将发送的字符串信息附加到文本框txtMsg上
  209. }
  210. catch (Exception)
  211. {
  212. if (socketServer.RemoteEndPoint != null)
  213. {
  214. }
  215. if (list.Contains(socketServer))
  216. {
  217. list.Remove(socketServer);
  218. }
  219. //关闭之前accept出来的和客户端进行通信的套接字
  220. socketServer.Close();
  221. break;
  222. }
  223. }
  224. if (socketServer != null)
  225. {
  226. if (socketServer.RemoteEndPoint != null)
  227. {
  228. }
  229. if (list.Contains(socketServer))
  230. {
  231. list.Remove(socketServer);
  232. }
  233. socketServer.Close();
  234. }
  235. }
  236. public void Close()
  237. {
  238. threadWatch.Abort();
  239. socketWatch.Close();
  240. isOpen = false;
  241. }
  242. }
  243. }