ModeBusTCPServer.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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. private Dictionary<string, string> returnvalue = new Dictionary<string, string>();
  15. Thread threadWatch = null; //负责监听客户端的线程
  16. Socket socketWatch = null; //负责监听客户端的套接字
  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 Dictionary<string, string> Returnvalue
  62. {
  63. get
  64. {
  65. return returnvalue;
  66. }
  67. set
  68. {
  69. returnvalue = value;
  70. }
  71. }
  72. public Dictionary<string, string> ReceiveCoding = new Dictionary<string, string>();
  73. private string iP;
  74. private string port;
  75. public List<Socket> list = new List<Socket>();
  76. public ModeBusTCPServer()
  77. {
  78. }
  79. public bool Open()
  80. {
  81. try
  82. {
  83. IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());
  84. for (int i = 0; i < IpEntry.AddressList.Length; i++)
  85. {
  86. if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
  87. iP = IpEntry.AddressList[i].ToString();
  88. }
  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 receiveCoding, string Command)
  115. {
  116. if (!ReceiveCoding.ContainsKey(IPAddress))
  117. ReceiveCoding.Add(IPAddress, receiveCoding);
  118. foreach (Socket item in list)
  119. {
  120. if (item != null)
  121. {
  122. if (item.RemoteEndPoint != null)
  123. {
  124. if (item.RemoteEndPoint.ToString() == IPAddress)
  125. {
  126. switch (EnCoding)
  127. {
  128. case "UTF-8":
  129. item.Send(Encoding.UTF8.GetBytes(Command));
  130. break;
  131. case "ASCII":
  132. byte[] array = Encoding.ASCII.GetBytes(Command);
  133. string str = null;
  134. for (int i = 0; i < array.Length; i++)
  135. {
  136. int asciicode = (int)(array[i]);
  137. str += Convert.ToString(asciicode) + " ";
  138. }
  139. item.Send(Encoding.ASCII.GetBytes(str));
  140. break;
  141. case "Hexadecimal":
  142. char[] values = Command.ToCharArray();
  143. string strH = null;
  144. foreach (char letter in values)
  145. {
  146. // Get the integral value of the character.
  147. int value = Convert.ToInt32(letter);
  148. // Convert the decimal value to a hexadecimal value in string form.
  149. string hexOutput = String.Format("{0:X}", value);
  150. strH += hexOutput + " ";
  151. }
  152. item.Send(Encoding.UTF8.GetBytes(strH));
  153. break;
  154. }
  155. }
  156. receiveData = false;
  157. }
  158. else
  159. {
  160. if (list.Count > 0)
  161. {
  162. if (IPAddress == "")
  163. IPAddress = list[0].RemoteEndPoint.ToString();
  164. }
  165. else
  166. IPAddress = "";
  167. if (list.Contains(item))
  168. {
  169. list.Remove(item);
  170. }
  171. //关闭之前accept出来的和客户端进行通信的套接字
  172. item.Close();
  173. }
  174. }
  175. }
  176. }
  177. private void WatchConnecting()
  178. {
  179. Socket connection = null;
  180. while (true) //持续不断监听客户端发来的请求
  181. {
  182. try
  183. {
  184. connection = socketWatch.Accept();
  185. }
  186. catch (Exception)
  187. {
  188. break;
  189. }
  190. //获取客户端的IP和端口号
  191. IPAddress clientIP = (connection.RemoteEndPoint as IPEndPoint).Address;
  192. int clientPort = (connection.RemoteEndPoint as IPEndPoint).Port;
  193. //让客户显示"连接成功的"的信息
  194. string sendmsg = "Connect Success!" + "LocalIP:" + clientIP + ",LocalPort" + clientPort.ToString();
  195. byte[] arrSendMsg = Encoding.UTF8.GetBytes(sendmsg);
  196. connection.Send(arrSendMsg);
  197. //客户端网络结点号
  198. string remoteEndPoint = connection.RemoteEndPoint.ToString();
  199. //显示与客户端连接情况
  200. IPEndPoint netpoint = connection.RemoteEndPoint as IPEndPoint;
  201. //创建一个通信线程
  202. ParameterizedThreadStart pts = new ParameterizedThreadStart(recv);
  203. Thread thread = new Thread(pts);
  204. //设置为后台线程,随着主线程退出而退出
  205. thread.IsBackground = true;
  206. //启动线程
  207. thread.Start(connection);
  208. list.Add(connection);
  209. }
  210. }
  211. void recv(object socketclientpara)
  212. {
  213. Socket socketServer = socketclientpara as Socket;
  214. while (true)
  215. {
  216. //创建一个内存缓冲区,其大小为1024*1024字节 即1M
  217. byte[] arrServerRecMsg = new byte[1024 * 1024];
  218. //将接收到的信息存入到内存缓冲区,并返回其字节数组的长度
  219. try
  220. {
  221. int length = socketServer.Receive(arrServerRecMsg);
  222. if (length == 0)
  223. {
  224. break;
  225. }
  226. if (ReceiveCoding.ContainsKey(socketServer.RemoteEndPoint.ToString()))
  227. {
  228. if (!returnvalue.ContainsKey(socketServer.RemoteEndPoint.ToString()))
  229. {
  230. switch (ReceiveCoding[socketServer.RemoteEndPoint.ToString()])
  231. {
  232. case "UTF-8":
  233. returnvalue.Add(socketServer.RemoteEndPoint.ToString(), Encoding.UTF8.GetString(arrServerRecMsg, 0, length));
  234. break;
  235. case "ASCII":
  236. returnvalue.Add(socketServer.RemoteEndPoint.ToString(), Encoding.ASCII.GetString(arrServerRecMsg, 0, length));
  237. break;
  238. case "Hexadecimal":
  239. returnvalue.Add(socketServer.RemoteEndPoint.ToString(), BaseUtil.ByteToHexadecimalString(arrServerRecMsg, length));
  240. break;
  241. default:
  242. break;
  243. }
  244. }
  245. }
  246. }
  247. catch (Exception)
  248. {
  249. if (socketServer.RemoteEndPoint != null)
  250. {
  251. }
  252. if (list.Contains(socketServer))
  253. {
  254. list.Remove(socketServer);
  255. }
  256. //关闭之前accept出来的和客户端进行通信的套接字
  257. socketServer.Close();
  258. break;
  259. }
  260. }
  261. receiveData = true;
  262. if (socketServer != null)
  263. {
  264. if (socketServer.RemoteEndPoint != null)
  265. {
  266. }
  267. if (list.Contains(socketServer))
  268. {
  269. list.Remove(socketServer);
  270. }
  271. socketServer.Close();
  272. }
  273. }
  274. public void Close()
  275. {
  276. threadWatch.Abort();
  277. socketWatch.Close();
  278. isOpen = false;
  279. }
  280. }
  281. }