using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Windows.Forms; namespace UAS_DeviceMonitor.PublicMethod { class ModeBusTCPServer { private bool isOpen = false; Thread threadWatch = null; //负责监听客户端的线程 Socket socketWatch = null; //负责监听客户端的套接字 public bool IsOpen { get { return isOpen; } set { isOpen = value; } } public string IP { get { return iP; } set { iP = value; } } public string Port { get { return port; } set { port = value; } } private string iP; private string port; public List list = new List(); public ModeBusTCPServer() { } public bool Open() { try { //定义一个套接字用于监听客户端发来的信息 包含3个参数(IP4寻址协议,流式连接,TCP协议) socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //服务端发送信息 需要1个IP地址和端口号 IPAddress ipaddress = IPAddress.Parse(iP); //将IP地址和端口号绑定到网络节点endpoint上 IPEndPoint endpoint = new IPEndPoint(ipaddress, int.Parse(port)); //监听绑定的网络节点 socketWatch.Bind(endpoint); //将套接字的监听队列长度限制为20 socketWatch.Listen(20); //创建一个监听线程 threadWatch = new Thread(WatchConnecting); //将窗体线程设置为与后台同步 threadWatch.IsBackground = true; //启动线程 threadWatch.Start(); isOpen = true; return true; } catch (Exception e) { MessageBox.Show(e.Message); return false; } } //private void SEND_Click(object sender, EventArgs e) //{ // foreach (Socket item in list) // { // if (item != null) // { // if (item.RemoteEndPoint != null) // { // if (item.RemoteEndPoint.ToString() == SelectIP.Text) // { // switch (Encodingbox.Text) // { // case "UTF-8": // item.Send(Encoding.UTF8.GetBytes(SENDMESSAGE.Text)); // break; // case "ASCII": // byte[] array = Encoding.ASCII.GetBytes(SENDMESSAGE.Text.Trim()); // string str = null; // for (int i = 0; i < array.Length; i++) // { // int asciicode = (int)(array[i]); // str += Convert.ToString(asciicode) + " "; // } // item.Send(Encoding.ASCII.GetBytes(str)); // break; // case "Hexadecimal": // char[] values = SENDMESSAGE.Text.ToCharArray(); // string strH = null; // foreach (char letter in values) // { // // Get the integral value of the character. // int value = Convert.ToInt32(letter); // // Convert the decimal value to a hexadecimal value in string form. // string hexOutput = String.Format("{0:X}", value); // strH += hexOutput + " "; // } // item.Send(Encoding.UTF8.GetBytes(strH)); // break; // } // } // } // else // { // int index = SelectIP.Items.IndexOf(item.RemoteEndPoint.ToString()); // SelectIP.Items.RemoveAt(index); // if (SelectIP.Items.Count > 0) // { // if (SelectIP.Text == "") // SelectIP.Text = SelectIP.Items[0].ToString(); // } // else // SelectIP.Text = ""; // if (list.Contains(item)) // { // list.Remove(item); // } // //关闭之前accept出来的和客户端进行通信的套接字 // item.Close(); // } // } // } //} private void WatchConnecting() { Socket connection = null; while (true) //持续不断监听客户端发来的请求 { try { connection = socketWatch.Accept(); } catch (Exception) { break; } //获取客户端的IP和端口号 IPAddress clientIP = (connection.RemoteEndPoint as IPEndPoint).Address; int clientPort = (connection.RemoteEndPoint as IPEndPoint).Port; //让客户显示"连接成功的"的信息 string sendmsg = "Connect Success!" + "LocalIP:" + clientIP + ",LocalPort" + clientPort.ToString(); byte[] arrSendMsg = Encoding.UTF8.GetBytes(sendmsg); connection.Send(arrSendMsg); //客户端网络结点号 string remoteEndPoint = connection.RemoteEndPoint.ToString(); //显示与客户端连接情况 //IPEndPoint netpoint = new IPEndPoint(clientIP,clientPort); IPEndPoint netpoint = connection.RemoteEndPoint as IPEndPoint; //创建一个通信线程 ParameterizedThreadStart pts = new ParameterizedThreadStart(recv); Thread thread = new Thread(pts); //设置为后台线程,随着主线程退出而退出 thread.IsBackground = true; //启动线程 thread.Start(connection); //创建一个通信线程 //ParameterizedThreadStart sed = new ParameterizedThreadStart(sends); //Thread threadsed = new Thread(sed); //设置为后台线程,随着主线程退出而退出 //threadsed.IsBackground = true; //启动线程 //threadsed.Start(connection); list.Add(connection); } } void recv(object socketclientpara) { Socket socketServer = socketclientpara as Socket; while (true) { //创建一个内存缓冲区,其大小为1024*1024字节 即1M byte[] arrServerRecMsg = new byte[1024 * 1024]; //将接收到的信息存入到内存缓冲区,并返回其字节数组的长度 try { int length = socketServer.Receive(arrServerRecMsg); if (length == 0) { break; } //将机器接受到的字节数组转换为人可以读懂的字符串 string strSRecMsg = Encoding.UTF8.GetString(arrServerRecMsg, 0, length); //将发送的字符串信息附加到文本框txtMsg上 } catch (Exception) { if (socketServer.RemoteEndPoint != null) { } if (list.Contains(socketServer)) { list.Remove(socketServer); } //关闭之前accept出来的和客户端进行通信的套接字 socketServer.Close(); break; } } if (socketServer != null) { if (socketServer.RemoteEndPoint != null) { } if (list.Contains(socketServer)) { list.Remove(socketServer); } socketServer.Close(); } } public void Close() { threadWatch.Abort(); socketWatch.Close(); isOpen = false; } public void SendOrder(string Code) { switch (Code) { default: break; } } } }