TcpServer.cs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Net.Sockets;
  7. using System.Text;
  8. using System.Threading;
  9. using System.Windows.Forms;
  10. namespace FileWatcher
  11. {
  12. public class TcpServer
  13. {
  14. //端口号
  15. private int SocketServerPort = 8800;
  16. //处理连接请求的线程
  17. private Thread acceptConnectReqThd;
  18. List<Socket> socket = new List<Socket>();
  19. Socket socketWatch;
  20. bool Watching;
  21. RichTextBox OperatResult;
  22. DataGridView dgv;
  23. public bool Start()
  24. {
  25. try
  26. {
  27. //创建一个socket对象
  28. socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  29. //获取IP
  30. IPAddress ip = IPAddress.Any;
  31. //创建端口号
  32. IPEndPoint port = new IPEndPoint(ip, SocketServerPort);
  33. //监听
  34. socketWatch.Bind(port);
  35. Console.WriteLine("监听成功");
  36. socketWatch.Listen(200); //设定最大的挂起长度
  37. //新建线程来处理连接请求
  38. acceptConnectReqThd = new Thread(AcceptConnectReqHandler);
  39. acceptConnectReqThd.IsBackground = true;
  40. acceptConnectReqThd.Start(socketWatch); //把socket对象当做参数传递给到线程里面的方法
  41. foreach (Form openForm in Application.OpenForms)
  42. {
  43. if (openForm is SOP)
  44. {
  45. form = openForm;
  46. }
  47. }
  48. OperatResult = (RichTextBox)form.Controls["OperatResult"];
  49. dgv = (DataGridView)form.Controls["SendDGV"];
  50. return true;
  51. }
  52. catch (Exception)
  53. {
  54. return false;
  55. }
  56. }
  57. private void AcceptConnectReqHandler(object _socket)
  58. {
  59. try
  60. {
  61. //服务端的socket对象
  62. Socket serverSocket = (Socket)_socket;
  63. Watching = true;
  64. while (Watching)
  65. {
  66. //获取客户端socket。Accept方法处理任何传入的连接请求,并返回可用于与远程主机通信数据的Socket对象,即客户端的socket。
  67. //这一句话会卡主线程。只要没有新的链接进来,就会一直卡主不动(等待中)。
  68. //收到连接事件后,会往下执行,通过while又回到这里继续等待
  69. Socket clientSocket = serverSocket.Accept();
  70. socket.Add(clientSocket);
  71. //创建接受客户端消息的线程
  72. Thread acceptMsgReqThd = new Thread(ReciveMsgReqHandler);
  73. acceptMsgReqThd.IsBackground = true;
  74. acceptMsgReqThd.Start(clientSocket);
  75. }
  76. }
  77. catch (Exception e)
  78. {
  79. Console.WriteLine("服务端处理连接事件异常:" + e.ToString());
  80. }
  81. }
  82. Form form = null;
  83. private void ReciveMsgReqHandler(object _socket)
  84. {
  85. Socket clientSocket = (Socket)_socket;
  86. try
  87. {
  88. while (true)
  89. {
  90. //客户端连接成功后,接受来自客户端的消息
  91. if (clientSocket == null)
  92. {
  93. continue;
  94. }
  95. byte[] buffer = new byte[1024]; //数据缓冲区。
  96. //实际接收到的有效字节数
  97. //Receive也是个卡线程的方法
  98. //Console.WriteLine("等待接受客户端的数据:");
  99. //OperatResult.AppendText("等待接受客户端的数据,"+ clientSocket+ "\n");
  100. Console.WriteLine("等待接受客户端的数:");
  101. int dataLength = clientSocket.Receive(buffer);
  102. Console.WriteLine("接受到客户端的数据,字节数:" + dataLength);
  103. //OperatResult.AppendText("接受到客户端的数据,字节数:" + dataLength);
  104. //如果客户端关闭,发送的数据就为空,就跳出循环
  105. if (dataLength == 0)
  106. {
  107. break;
  108. }
  109. //假设收到的是个字符串(先这么假定),转成字符串处理
  110. string strMsg = Encoding.UTF8.GetString(buffer, 0, dataLength);
  111. Console.WriteLine("接受到客户端的消息:" + strMsg);
  112. for (int i = 0; i < dgv.Rows.Count; i++)
  113. {
  114. if (dgv.Rows[i].Cells["fp_name"].Value.ToString().Replace(".jpg", "") == strMsg.Replace("成功", ""))
  115. {
  116. Console.WriteLine(dgv.Rows[i].Cells["fp_name"].Value.ToString().Replace(".jpg", "") + strMsg.Replace("成功", ""));
  117. dgv.Rows[i].Cells["issend"].Value = "发送成功";
  118. }
  119. }
  120. OperatResult.AppendText("接受到客户端的消息:" + strMsg);
  121. }
  122. //中止当前线程
  123. //Thread.CurrentThread.Abort();
  124. }
  125. catch (Exception e)
  126. {
  127. SocketException socketExp = e as SocketException;
  128. if (socketExp != null && socketExp.NativeErrorCode == 10054)
  129. {
  130. Console.WriteLine("socket客户端关闭:" + e.ToString());
  131. }
  132. else
  133. {
  134. Console.WriteLine("======接受消息异常:" + e.ToString());
  135. }
  136. //中止当前线程
  137. Thread.CurrentThread.Abort();
  138. }
  139. }
  140. public void Send(string Command)
  141. {
  142. try
  143. {
  144. Console.WriteLine(Command);
  145. foreach (Socket item in socket)
  146. {
  147. item.Send(Encoding.Default.GetBytes(Command));
  148. }
  149. }
  150. catch (Exception ex)
  151. {
  152. Console.WriteLine(ex.Message);
  153. }
  154. }
  155. public void Stop()
  156. {
  157. //acceptConnectReqThd.Interrupt();
  158. //acceptConnectReqThd.Abort();
  159. //foreach (Socket item in socket)
  160. //{
  161. // item.Disconnect(true);
  162. // item.Close();
  163. //}
  164. try
  165. {
  166. Watching = false;
  167. socketWatch.Close();
  168. socketWatch = null;
  169. socket.Clear();
  170. }
  171. catch (Exception ex)
  172. {
  173. Console.WriteLine(ex.Message + ex.StackTrace);
  174. }
  175. }
  176. }
  177. }