ModeBusTCPServer.cs 11 KB

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