using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Windows.Forms; namespace FileWatcher { public class TcpServer { //端口号 private int SocketServerPort = 8800; //处理连接请求的线程 private Thread acceptConnectReqThd; List socket = new List(); Socket socketWatch; bool Watching; RichTextBox OperatResult; DataGridView dgv; public bool Start() { try { //创建一个socket对象 socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //获取IP IPAddress ip = IPAddress.Any; //创建端口号 IPEndPoint port = new IPEndPoint(ip, SocketServerPort); //监听 socketWatch.Bind(port); Console.WriteLine("监听成功"); socketWatch.Listen(200); //设定最大的挂起长度 //新建线程来处理连接请求 acceptConnectReqThd = new Thread(AcceptConnectReqHandler); acceptConnectReqThd.IsBackground = true; acceptConnectReqThd.Start(socketWatch); //把socket对象当做参数传递给到线程里面的方法 foreach (Form openForm in Application.OpenForms) { if (openForm is SOP) { form = openForm; } } OperatResult = (RichTextBox)form.Controls["OperatResult"]; dgv = (DataGridView)form.Controls["SendDGV"]; return true; } catch (Exception) { return false; } } private void AcceptConnectReqHandler(object _socket) { try { //服务端的socket对象 Socket serverSocket = (Socket)_socket; Watching = true; while (Watching) { //获取客户端socket。Accept方法处理任何传入的连接请求,并返回可用于与远程主机通信数据的Socket对象,即客户端的socket。 //这一句话会卡主线程。只要没有新的链接进来,就会一直卡主不动(等待中)。 //收到连接事件后,会往下执行,通过while又回到这里继续等待 Socket clientSocket = serverSocket.Accept(); socket.Add(clientSocket); //创建接受客户端消息的线程 Thread acceptMsgReqThd = new Thread(ReciveMsgReqHandler); acceptMsgReqThd.IsBackground = true; acceptMsgReqThd.Start(clientSocket); } } catch (Exception e) { Console.WriteLine("服务端处理连接事件异常:" + e.ToString()); } } Form form = null; private void ReciveMsgReqHandler(object _socket) { Socket clientSocket = (Socket)_socket; try { while (true) { //客户端连接成功后,接受来自客户端的消息 if (clientSocket == null) { continue; } byte[] buffer = new byte[1024]; //数据缓冲区。 //实际接收到的有效字节数 //Receive也是个卡线程的方法 //Console.WriteLine("等待接受客户端的数据:"); //OperatResult.AppendText("等待接受客户端的数据,"+ clientSocket+ "\n"); Console.WriteLine("等待接受客户端的数:"); int dataLength = clientSocket.Receive(buffer); Console.WriteLine("接受到客户端的数据,字节数:" + dataLength); //OperatResult.AppendText("接受到客户端的数据,字节数:" + dataLength); //如果客户端关闭,发送的数据就为空,就跳出循环 if (dataLength == 0) { break; } //假设收到的是个字符串(先这么假定),转成字符串处理 string strMsg = Encoding.UTF8.GetString(buffer, 0, dataLength); Console.WriteLine("接受到客户端的消息:" + strMsg); for (int i = 0; i < dgv.Rows.Count; i++) { if (dgv.Rows[i].Cells["fp_name"].Value.ToString().Replace(".jpg", "") == strMsg.Replace("成功", "")) { Console.WriteLine(dgv.Rows[i].Cells["fp_name"].Value.ToString().Replace(".jpg", "") + strMsg.Replace("成功", "")); dgv.Rows[i].Cells["issend"].Value = "发送成功"; } } OperatResult.AppendText("接受到客户端的消息:" + strMsg); } //中止当前线程 //Thread.CurrentThread.Abort(); } catch (Exception e) { SocketException socketExp = e as SocketException; if (socketExp != null && socketExp.NativeErrorCode == 10054) { Console.WriteLine("socket客户端关闭:" + e.ToString()); } else { Console.WriteLine("======接受消息异常:" + e.ToString()); } //中止当前线程 Thread.CurrentThread.Abort(); } } public void Send(string Command) { try { Console.WriteLine(Command); foreach (Socket item in socket) { item.Send(Encoding.Default.GetBytes(Command)); } } catch (Exception ex) { Console.WriteLine(ex.Message); } } public void Stop() { //acceptConnectReqThd.Interrupt(); //acceptConnectReqThd.Abort(); //foreach (Socket item in socket) //{ // item.Disconnect(true); // item.Close(); //} try { Watching = false; socketWatch.Close(); socketWatch = null; socket.Clear(); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); } } } }