ModeBusTCPServer.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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. if (SelectIP.Items.Count > 0)
  112. {
  113. if (SelectIP.Text == "")
  114. SelectIP.Text = SelectIP.Items[0].ToString();
  115. }
  116. else
  117. SelectIP.Text = "";
  118. richtext.AppendText("客户端" + item.RemoteEndPoint + "已经中断连接" + "\r\n");
  119. if (list.Contains(item))
  120. {
  121. list.Remove(item);
  122. }
  123. //关闭之前accept出来的和客户端进行通信的套接字
  124. item.Close();
  125. }
  126. }
  127. }
  128. }
  129. private void WatchConnecting()
  130. {
  131. Socket connection = null;
  132. while (true) //持续不断监听客户端发来的请求
  133. {
  134. try
  135. {
  136. connection = socketWatch.Accept();
  137. }
  138. catch (Exception)
  139. {
  140. break;
  141. }
  142. //获取客户端的IP和端口号
  143. IPAddress clientIP = (connection.RemoteEndPoint as IPEndPoint).Address;
  144. int clientPort = (connection.RemoteEndPoint as IPEndPoint).Port;
  145. //让客户显示"连接成功的"的信息
  146. string sendmsg = "连接服务端成功!\r\n" + "本地IP:" + clientIP + ",本地端口" + clientPort.ToString();
  147. byte[] arrSendMsg = Encoding.UTF8.GetBytes(sendmsg);
  148. connection.Send(arrSendMsg);
  149. //客户端网络结点号
  150. string remoteEndPoint = connection.RemoteEndPoint.ToString();
  151. //显示与客户端连接情况
  152. richtext.AppendText("成功与" + remoteEndPoint + "客户端建立连接!\t\n");
  153. SelectIP.Items.Add(clientIP + ":" + clientPort.ToString());
  154. SelectIP.SelectedItem = clientIP + ":" + clientPort.ToString();
  155. //IPEndPoint netpoint = new IPEndPoint(clientIP,clientPort);
  156. IPEndPoint netpoint = connection.RemoteEndPoint as IPEndPoint;
  157. //创建一个通信线程
  158. ParameterizedThreadStart pts = new ParameterizedThreadStart(recv);
  159. Thread thread = new Thread(pts);
  160. //设置为后台线程,随着主线程退出而退出
  161. thread.IsBackground = true;
  162. //启动线程
  163. thread.Start(connection);
  164. //创建一个通信线程
  165. //ParameterizedThreadStart sed = new ParameterizedThreadStart(sends);
  166. //Thread threadsed = new Thread(sed);
  167. //设置为后台线程,随着主线程退出而退出
  168. //threadsed.IsBackground = true;
  169. //启动线程
  170. //threadsed.Start(connection);
  171. list.Add(connection);
  172. }
  173. }
  174. void recv(object socketclientpara)
  175. {
  176. Socket socketServer = socketclientpara as Socket;
  177. while (true)
  178. {
  179. //创建一个内存缓冲区,其大小为1024*1024字节 即1M
  180. byte[] arrServerRecMsg = new byte[1024 * 1024];
  181. //将接收到的信息存入到内存缓冲区,并返回其字节数组的长度
  182. try
  183. {
  184. int length = socketServer.Receive(arrServerRecMsg);
  185. if (length == 0)
  186. {
  187. break;
  188. }
  189. //将机器接受到的字节数组转换为人可以读懂的字符串
  190. string strSRecMsg = Encoding.UTF8.GetString(arrServerRecMsg, 0, length);
  191. //将发送的字符串信息附加到文本框txtMsg上
  192. richtext.AppendText("客户端:" + socketServer.RemoteEndPoint + ",\r\n" + strSRecMsg + "\r\n\n");
  193. }
  194. catch (Exception)
  195. {
  196. if (socketServer.RemoteEndPoint != null)
  197. {
  198. //提示套接字监听异常
  199. int index = SelectIP.Items.IndexOf(socketServer.RemoteEndPoint.ToString());
  200. SelectIP.Items.RemoveAt(index);
  201. if (SelectIP.Items.Count > 0)
  202. {
  203. if (SelectIP.Text == "")
  204. SelectIP.Text = SelectIP.Items[0].ToString();
  205. }
  206. else
  207. SelectIP.Text = "";
  208. richtext.AppendText("客户端" + socketServer.RemoteEndPoint + "已经中断连接" + "\r\n");
  209. }
  210. if (list.Contains(socketServer))
  211. {
  212. list.Remove(socketServer);
  213. }
  214. //关闭之前accept出来的和客户端进行通信的套接字
  215. socketServer.Close();
  216. break;
  217. }
  218. }
  219. if (socketServer != null)
  220. {
  221. if (socketServer.RemoteEndPoint != null)
  222. {
  223. int index = SelectIP.Items.IndexOf(socketServer.RemoteEndPoint.ToString());
  224. SelectIP.Items.RemoveAt(index);
  225. if (SelectIP.Items.Count > 0)
  226. {
  227. if (SelectIP.Text == "")
  228. SelectIP.Text = SelectIP.Items[0].ToString();
  229. }
  230. else
  231. SelectIP.Text = "";
  232. richtext.AppendText("客户端" + socketServer.RemoteEndPoint + "已经中断连接" + "\r\n");
  233. }
  234. if (list.Contains(socketServer))
  235. {
  236. list.Remove(socketServer);
  237. }
  238. socketServer.Close();
  239. }
  240. }
  241. public void Close()
  242. {
  243. threadWatch.Abort();
  244. socketWatch.Close();
  245. isOpen = false;
  246. }
  247. public void SendOrder(string Code)
  248. {
  249. switch (Code)
  250. {
  251. default:
  252. break;
  253. }
  254. }
  255. }
  256. }