ModeBusTCPServer.cs 11 KB

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