ModeBusTCPServer.cs 10.0 KB

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