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