ModeBusTCPServer.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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. 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. //去除指令空格
  123. Command = Command.Replace(" ", "");
  124. byte[] arr = new byte[Command.Length / 2];
  125. foreach (Socket item in list)
  126. {
  127. if (item != null)
  128. {
  129. if (item.RemoteEndPoint != null)
  130. {
  131. if (item.RemoteEndPoint.ToString() == IPAddress)
  132. {
  133. switch (EnCoding)
  134. {
  135. case "UTF-8":
  136. item.Send(Encoding.UTF8.GetBytes(Command));
  137. break;
  138. case "ASCII":
  139. byte[] array = Encoding.ASCII.GetBytes(Command);
  140. string str = null;
  141. for (int i = 0; i < array.Length; i++)
  142. {
  143. int asciicode = (int)(array[i]);
  144. str += Convert.ToString(asciicode) + " ";
  145. }
  146. item.Send(Encoding.ASCII.GetBytes(str));
  147. break;
  148. case "Hexadecimal":
  149. for (int i = 0; i < Command.Length / 2; i++)
  150. {
  151. arr[i] = (byte)Convert.ToInt32(Command.Substring(i * 2, 2), 16);
  152. }
  153. item.Send(arr);
  154. break;
  155. }
  156. }
  157. receiveData = false;
  158. }
  159. else
  160. {
  161. if (list.Count > 0)
  162. {
  163. if (IPAddress == "")
  164. IPAddress = list[0].RemoteEndPoint.ToString();
  165. }
  166. else
  167. IPAddress = "";
  168. if (list.Contains(item))
  169. {
  170. list.Remove(item);
  171. }
  172. //关闭之前accept出来的和客户端进行通信的套接字
  173. item.Close();
  174. }
  175. }
  176. }
  177. }
  178. private void WatchConnecting()
  179. {
  180. Socket connection = null;
  181. while (true) //持续不断监听客户端发来的请求
  182. {
  183. try
  184. {
  185. connection = socketWatch.Accept();
  186. }
  187. catch (Exception)
  188. {
  189. break;
  190. }
  191. //获取客户端的IP和端口号
  192. IPAddress clientIP = (connection.RemoteEndPoint as IPEndPoint).Address;
  193. int clientPort = (connection.RemoteEndPoint as IPEndPoint).Port;
  194. Console.WriteLine(clientIP);
  195. Console.WriteLine(clientPort);
  196. //让客户显示"连接成功的"的信息
  197. string sendmsg = "Connect Success!" + "LocalIP:" + clientIP + ",LocalPort" + clientPort.ToString();
  198. byte[] arrSendMsg = Encoding.UTF8.GetBytes(sendmsg);
  199. connection.Send(arrSendMsg);
  200. //客户端网络结点号
  201. string remoteEndPoint = connection.RemoteEndPoint.ToString();
  202. //显示与客户端连接情况
  203. IPEndPoint netpoint = connection.RemoteEndPoint as IPEndPoint;
  204. //创建一个通信线程
  205. ParameterizedThreadStart pts = new ParameterizedThreadStart(recv);
  206. Thread thread = new Thread(pts);
  207. //设置为后台线程,随着主线程退出而退出
  208. thread.IsBackground = true;
  209. //启动线程
  210. thread.Start(connection);
  211. list.Add(connection);
  212. }
  213. }
  214. void recv(object socketclientpara)
  215. {
  216. Socket socketServer = socketclientpara as Socket;
  217. while (true)
  218. {
  219. //创建一个内存缓冲区,其大小为1024*1024字节 即1M
  220. byte[] arrServerRecMsg = new byte[1024 * 1024];
  221. //将接收到的信息存入到内存缓冲区,并返回其字节数组的长度
  222. try
  223. {
  224. int length = socketServer.Receive(arrServerRecMsg);
  225. if (length == 0)
  226. {
  227. break;
  228. }
  229. if (ReceiveCoding.ContainsKey(socketServer.RemoteEndPoint.ToString()))
  230. {
  231. if (!returnvalue.ContainsKey(socketServer.RemoteEndPoint.ToString()))
  232. {
  233. switch (ReceiveCoding[socketServer.RemoteEndPoint.ToString()])
  234. {
  235. case "UTF-8":
  236. returnvalue.Add(socketServer.RemoteEndPoint.ToString(), Encoding.UTF8.GetString(arrServerRecMsg, 0, length));
  237. break;
  238. case "ASCII":
  239. returnvalue.Add(socketServer.RemoteEndPoint.ToString(), Encoding.ASCII.GetString(arrServerRecMsg, 0, length));
  240. break;
  241. case "Hexadecimal":
  242. returnvalue.Add(socketServer.RemoteEndPoint.ToString(), BaseUtil.ByteToHexadecimalString(arrServerRecMsg, length));
  243. break;
  244. default:
  245. break;
  246. }
  247. }
  248. }
  249. }
  250. catch (Exception)
  251. {
  252. if (socketServer.RemoteEndPoint != null)
  253. {
  254. }
  255. if (list.Contains(socketServer))
  256. {
  257. list.Remove(socketServer);
  258. }
  259. //关闭之前accept出来的和客户端进行通信的套接字
  260. socketServer.Close();
  261. break;
  262. }
  263. }
  264. receiveData = true;
  265. if (socketServer != null)
  266. {
  267. if (socketServer.RemoteEndPoint != null)
  268. {
  269. }
  270. if (list.Contains(socketServer))
  271. {
  272. list.Remove(socketServer);
  273. }
  274. socketServer.Close();
  275. }
  276. }
  277. public void Close()
  278. {
  279. threadWatch.Abort();
  280. socketWatch.Close();
  281. isOpen = false;
  282. }
  283. }
  284. }