ModeBusTCPServer.cs 9.6 KB

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