ModeBusTCPServer.cs 12 KB

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