ModeBusTCPServer.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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. Button SEND;
  54. RichTextAutoBottom SENDMESSAGE;
  55. public List<Socket> list = new List<Socket>();
  56. private Boolean messageflag = false;
  57. public ModeBusTCPServer()
  58. {
  59. }
  60. public bool Open()
  61. {
  62. try
  63. {
  64. SelectIP = Application.OpenForms["MainWindow"].Controls["SelectIP"] as ComboBox;
  65. richtext = Application.OpenForms["MainWindow"].Controls["Result"] as RichTextAutoBottom;
  66. SEND = Application.OpenForms["MainWindow"].Controls["SEND"] as Button;
  67. SENDMESSAGE = Application.OpenForms["MainWindow"].Controls["SENDMESSAGE"] as RichTextAutoBottom;
  68. SEND.Click += SEND_Click;
  69. //定义一个套接字用于监听客户端发来的信息 包含3个参数(IP4寻址协议,流式连接,TCP协议)
  70. socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  71. //服务端发送信息 需要1个IP地址和端口号
  72. IPAddress ipaddress = IPAddress.Parse(iP);
  73. //将IP地址和端口号绑定到网络节点endpoint上
  74. IPEndPoint endpoint = new IPEndPoint(ipaddress, int.Parse(port));
  75. //监听绑定的网络节点
  76. socketWatch.Bind(endpoint);
  77. //将套接字的监听队列长度限制为20
  78. socketWatch.Listen(20);
  79. //创建一个监听线程
  80. threadWatch = new Thread(WatchConnecting);
  81. //将窗体线程设置为与后台同步
  82. threadWatch.IsBackground = true;
  83. //启动线程
  84. threadWatch.Start();
  85. isOpen = true;
  86. return true;
  87. }
  88. catch (Exception e)
  89. {
  90. MessageBox.Show(e.Message);
  91. return false;
  92. }
  93. }
  94. private void SEND_Click(object sender, EventArgs e)
  95. {
  96. foreach (Socket item in list)
  97. {
  98. if (item != null)
  99. {
  100. if (item.RemoteEndPoint != null)
  101. {
  102. if (item.RemoteEndPoint.ToString() == SelectIP.Text)
  103. {
  104. item.Send(Encoding.UTF8.GetBytes("\n" + SENDMESSAGE.Text));
  105. }
  106. }
  107. else
  108. {
  109. int index = SelectIP.Items.IndexOf(item.RemoteEndPoint.ToString());
  110. SelectIP.Items.RemoveAt(index);
  111. SelectIP.Update();
  112. richtext.AppendText("客户端" + item.RemoteEndPoint + "已经中断连接" + "\r\n");
  113. if (list.Contains(item))
  114. {
  115. list.Remove(item);
  116. }
  117. //关闭之前accept出来的和客户端进行通信的套接字
  118. item.Close();
  119. }
  120. }
  121. }
  122. }
  123. private void WatchConnecting()
  124. {
  125. Socket connection = null;
  126. while (true) //持续不断监听客户端发来的请求
  127. {
  128. try
  129. {
  130. connection = socketWatch.Accept();
  131. }
  132. catch (Exception)
  133. {
  134. break;
  135. }
  136. //获取客户端的IP和端口号
  137. IPAddress clientIP = (connection.RemoteEndPoint as IPEndPoint).Address;
  138. int clientPort = (connection.RemoteEndPoint as IPEndPoint).Port;
  139. //让客户显示"连接成功的"的信息
  140. string sendmsg = "连接服务端成功!\r\n" + "本地IP:" + clientIP + ",本地端口" + clientPort.ToString();
  141. byte[] arrSendMsg = Encoding.UTF8.GetBytes(sendmsg);
  142. connection.Send(arrSendMsg);
  143. //客户端网络结点号
  144. string remoteEndPoint = connection.RemoteEndPoint.ToString();
  145. //显示与客户端连接情况
  146. richtext.AppendText("成功与" + remoteEndPoint + "客户端建立连接!\t\n");
  147. SelectIP.Items.Add(clientIP + ":" + clientPort.ToString());
  148. SelectIP.SelectedItem = clientIP + ":" + clientPort.ToString();
  149. //IPEndPoint netpoint = new IPEndPoint(clientIP,clientPort);
  150. IPEndPoint netpoint = connection.RemoteEndPoint as IPEndPoint;
  151. //创建一个通信线程
  152. ParameterizedThreadStart pts = new ParameterizedThreadStart(recv);
  153. Thread thread = new Thread(pts);
  154. //设置为后台线程,随着主线程退出而退出
  155. thread.IsBackground = true;
  156. //启动线程
  157. thread.Start(connection);
  158. //创建一个通信线程
  159. //ParameterizedThreadStart sed = new ParameterizedThreadStart(sends);
  160. //Thread threadsed = new Thread(sed);
  161. //设置为后台线程,随着主线程退出而退出
  162. //threadsed.IsBackground = true;
  163. //启动线程
  164. //threadsed.Start(connection);
  165. list.Add(connection);
  166. }
  167. }
  168. void recv(object socketclientpara)
  169. {
  170. Socket socketServer = socketclientpara as Socket;
  171. while (true)
  172. {
  173. //创建一个内存缓冲区,其大小为1024*1024字节 即1M
  174. byte[] arrServerRecMsg = new byte[1024 * 1024];
  175. //将接收到的信息存入到内存缓冲区,并返回其字节数组的长度
  176. try
  177. {
  178. int length = socketServer.Receive(arrServerRecMsg);
  179. if (length == 0)
  180. {
  181. break;
  182. }
  183. //将机器接受到的字节数组转换为人可以读懂的字符串
  184. string strSRecMsg = Encoding.UTF8.GetString(arrServerRecMsg, 0, length);
  185. //将发送的字符串信息附加到文本框txtMsg上
  186. richtext.AppendText("客户端:" + socketServer.RemoteEndPoint + ",\r\n" + strSRecMsg + "\r\n\n");
  187. }
  188. catch (Exception)
  189. {
  190. if (socketServer.RemoteEndPoint != null)
  191. {
  192. //提示套接字监听异常
  193. int index = SelectIP.Items.IndexOf(socketServer.RemoteEndPoint.ToString());
  194. SelectIP.Items.RemoveAt(index);
  195. SelectIP.Update();
  196. richtext.AppendText("客户端" + socketServer.RemoteEndPoint + "已经中断连接" + "\r\n");
  197. }
  198. if (list.Contains(socketServer))
  199. {
  200. list.Remove(socketServer);
  201. }
  202. //关闭之前accept出来的和客户端进行通信的套接字
  203. socketServer.Close();
  204. break;
  205. }
  206. }
  207. if (socketServer != null)
  208. {
  209. if (socketServer.RemoteEndPoint != null)
  210. {
  211. int index = SelectIP.Items.IndexOf(socketServer.RemoteEndPoint.ToString());
  212. SelectIP.Items.RemoveAt(index);
  213. SelectIP.Update();
  214. richtext.AppendText("客户端" + socketServer.RemoteEndPoint + "已经中断连接" + "\r\n");
  215. }
  216. if (list.Contains(socketServer))
  217. {
  218. list.Remove(socketServer);
  219. }
  220. socketServer.Close();
  221. }
  222. }
  223. public void Close()
  224. {
  225. threadWatch.Abort();
  226. socketWatch.Close();
  227. isOpen = false;
  228. }
  229. public void SendOrder(string Code)
  230. {
  231. switch (Code)
  232. {
  233. default:
  234. break;
  235. }
  236. }
  237. }
  238. }