ModeBusTCPServer.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. case "LRC":
  134. string message = SENDMESSAGE.Text.Trim();
  135. if (message.Length % 2 != 0) {
  136. message = message + "0";
  137. }
  138. int LRC = 0x0;
  139. for (int i = 0; i < message.Length; i=i+2)
  140. {
  141. int inside =int.Parse(message.Substring(i,1).ToString()+ message.Substring(i+1,1).ToString(), System.Globalization.NumberStyles.HexNumber);
  142. LRC += inside;
  143. }
  144. string _LRC = string.Format("{0:X2}", LRC);
  145. string LRCre = "";
  146. for (int i = 0; i < _LRC.Length; i++)
  147. {
  148. int index;
  149. if (i != _LRC.Length - 1)
  150. {
  151. index = 0xF - int.Parse(_LRC.Substring(i, 1).ToString(), System.Globalization.NumberStyles.HexNumber);
  152. }else
  153. index = 0xF - int.Parse(_LRC.Substring(i, 1).ToString(), System.Globalization.NumberStyles.HexNumber)+1;
  154. LRCre += string.Format("{0:X}", index);
  155. }
  156. item.Send(Encoding.UTF8.GetBytes(LRCre.ToString()));
  157. break;
  158. }
  159. }
  160. }
  161. else
  162. {
  163. int index = SelectIP.Items.IndexOf(item.RemoteEndPoint.ToString());
  164. SelectIP.Items.RemoveAt(index);
  165. if (SelectIP.Items.Count > 0)
  166. {
  167. if (SelectIP.Text == "")
  168. SelectIP.Text = SelectIP.Items[0].ToString();
  169. }
  170. else
  171. SelectIP.Text = "";
  172. richtext.AppendText("客户端" + item.RemoteEndPoint + "已经中断连接" + "\r\n");
  173. if (list.Contains(item))
  174. {
  175. list.Remove(item);
  176. }
  177. //关闭之前accept出来的和客户端进行通信的套接字
  178. item.Close();
  179. }
  180. }
  181. }
  182. }
  183. private void WatchConnecting()
  184. {
  185. Socket connection = null;
  186. while (true) //持续不断监听客户端发来的请求
  187. {
  188. try
  189. {
  190. connection = socketWatch.Accept();
  191. }
  192. catch (Exception)
  193. {
  194. break;
  195. }
  196. //获取客户端的IP和端口号
  197. IPAddress clientIP = (connection.RemoteEndPoint as IPEndPoint).Address;
  198. int clientPort = (connection.RemoteEndPoint as IPEndPoint).Port;
  199. //让客户显示"连接成功的"的信息
  200. string sendmsg = "Connect Success!" + "LocalIP:" + clientIP + ",LocalPort" + clientPort.ToString();
  201. byte[] arrSendMsg = Encoding.UTF8.GetBytes(sendmsg);
  202. connection.Send(arrSendMsg);
  203. //客户端网络结点号
  204. string remoteEndPoint = connection.RemoteEndPoint.ToString();
  205. //显示与客户端连接情况
  206. richtext.AppendText("成功与" + remoteEndPoint + "客户端建立连接!\t\n");
  207. SelectIP.Items.Add(clientIP + ":" + clientPort.ToString());
  208. SelectIP.SelectedItem = clientIP + ":" + clientPort.ToString();
  209. //IPEndPoint netpoint = new IPEndPoint(clientIP,clientPort);
  210. IPEndPoint netpoint = connection.RemoteEndPoint as IPEndPoint;
  211. //创建一个通信线程
  212. ParameterizedThreadStart pts = new ParameterizedThreadStart(recv);
  213. Thread thread = new Thread(pts);
  214. //设置为后台线程,随着主线程退出而退出
  215. thread.IsBackground = true;
  216. //启动线程
  217. thread.Start(connection);
  218. //创建一个通信线程
  219. //ParameterizedThreadStart sed = new ParameterizedThreadStart(sends);
  220. //Thread threadsed = new Thread(sed);
  221. //设置为后台线程,随着主线程退出而退出
  222. //threadsed.IsBackground = true;
  223. //启动线程
  224. //threadsed.Start(connection);
  225. list.Add(connection);
  226. }
  227. }
  228. void recv(object socketclientpara)
  229. {
  230. Socket socketServer = socketclientpara as Socket;
  231. while (true)
  232. {
  233. //创建一个内存缓冲区,其大小为1024*1024字节 即1M
  234. byte[] arrServerRecMsg = new byte[1024 * 1024];
  235. //将接收到的信息存入到内存缓冲区,并返回其字节数组的长度
  236. try
  237. {
  238. int length = socketServer.Receive(arrServerRecMsg);
  239. if (length == 0)
  240. {
  241. break;
  242. }
  243. //将机器接受到的字节数组转换为人可以读懂的字符串
  244. string strSRecMsg = Encoding.UTF8.GetString(arrServerRecMsg, 0, length);
  245. //将发送的字符串信息附加到文本框txtMsg上
  246. richtext.AppendText("客户端:" + socketServer.RemoteEndPoint + ",\r\n" + strSRecMsg + "\r\n\n");
  247. }
  248. catch (Exception)
  249. {
  250. if (socketServer.RemoteEndPoint != null)
  251. {
  252. //提示套接字监听异常
  253. int index = SelectIP.Items.IndexOf(socketServer.RemoteEndPoint.ToString());
  254. SelectIP.Items.RemoveAt(index);
  255. if (SelectIP.Items.Count > 0)
  256. {
  257. if (SelectIP.Text == "")
  258. SelectIP.Text = SelectIP.Items[0].ToString();
  259. }
  260. else
  261. SelectIP.Text = "";
  262. richtext.AppendText("客户端" + socketServer.RemoteEndPoint + "已经中断连接" + "\r\n");
  263. }
  264. if (list.Contains(socketServer))
  265. {
  266. list.Remove(socketServer);
  267. }
  268. //关闭之前accept出来的和客户端进行通信的套接字
  269. socketServer.Close();
  270. break;
  271. }
  272. }
  273. if (socketServer != null)
  274. {
  275. if (socketServer.RemoteEndPoint != null)
  276. {
  277. int index = SelectIP.Items.IndexOf(socketServer.RemoteEndPoint.ToString());
  278. SelectIP.Items.RemoveAt(index);
  279. if (SelectIP.Items.Count > 0)
  280. {
  281. if (SelectIP.Text == "")
  282. SelectIP.Text = SelectIP.Items[0].ToString();
  283. }
  284. else
  285. SelectIP.Text = "";
  286. richtext.AppendText("客户端" + socketServer.RemoteEndPoint + "已经中断连接" + "\r\n");
  287. }
  288. if (list.Contains(socketServer))
  289. {
  290. list.Remove(socketServer);
  291. }
  292. socketServer.Close();
  293. }
  294. }
  295. public void Close()
  296. {
  297. threadWatch.Abort();
  298. socketWatch.Close();
  299. isOpen = false;
  300. }
  301. public void SendOrder(string Code)
  302. {
  303. switch (Code)
  304. {
  305. default:
  306. break;
  307. }
  308. }
  309. }
  310. }