using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace UAS_PLCDataReader.PublicMethod { class ModeBusTCPServer { private bool isOpen = false; private bool receiveData; private Dictionary returnvalue = new Dictionary(); 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; } } public bool ReceiveData { get { return receiveData; } set { receiveData = value; } } public Dictionary Returnvalue { get { return returnvalue; } set { returnvalue = value; } } public Dictionary ReceiveCoding = new Dictionary(); private string iP; private string port; public List list = new List(); public ModeBusTCPServer() { } public bool Open() { try { IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName()); for (int i = 0; i < IpEntry.AddressList.Length; i++) { if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork) { iP = IpEntry.AddressList[i].ToString(); } } //定义一个套接字用于监听客户端发来的信息 包含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, 4001); //监听绑定的网络节点 socketWatch.Bind(endpoint); //将套接字的监听队列长度限制为20 socketWatch.Listen(20); Task.Factory.StartNew(WatchConnecting, TaskCreationOptions.LongRunning); ////创建一个监听线程 //threadWatch = new Thread(WatchConnecting); ////将窗体线程设置为与后台同步 //threadWatch.IsBackground = true; ////启动线程 //threadWatch.Start(); isOpen = true; return true; } catch (Exception e) { MessageBox.Show(e.Message); return false; } } public void Send(string IPAddress, string EnCoding, string receiveCoding, string Command) { if (!ReceiveCoding.ContainsKey(IPAddress)) ReceiveCoding.Add(IPAddress, receiveCoding); //去除指令空格 Command = Command.Replace(" ", ""); byte[] arr = new byte[Command.Length / 2]; foreach (Socket item in list) { if (item != null) { if (item.RemoteEndPoint != null) { if (item.RemoteEndPoint.ToString() == IPAddress) { switch (EnCoding) { case "UTF-8": item.Send(Encoding.UTF8.GetBytes(Command)); break; case "ASCII": byte[] array = Encoding.ASCII.GetBytes(Command); 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": for (int i = 0; i < Command.Length / 2; i++) { arr[i] = (byte)Convert.ToInt32(Command.Substring(i * 2, 2), 16); } item.Send(arr); break; } } receiveData = false; } else { if (list.Count > 0) { if (IPAddress == "") IPAddress = list[0].RemoteEndPoint.ToString(); } else IPAddress = ""; 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; Console.WriteLine(clientIP); Console.WriteLine(clientPort); //让客户显示"连接成功的"的信息 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 = connection.RemoteEndPoint as IPEndPoint; //创建一个通信线程 ParameterizedThreadStart pts = new ParameterizedThreadStart(recv); Thread thread = new Thread(pts); //设置为后台线程,随着主线程退出而退出 thread.IsBackground = true; //启动线程 thread.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; } if (ReceiveCoding.ContainsKey(socketServer.RemoteEndPoint.ToString())) { if (!returnvalue.ContainsKey(socketServer.RemoteEndPoint.ToString())) { switch (ReceiveCoding[socketServer.RemoteEndPoint.ToString()]) { case "UTF-8": returnvalue.Add(socketServer.RemoteEndPoint.ToString(), Encoding.UTF8.GetString(arrServerRecMsg, 0, length)); break; case "ASCII": returnvalue.Add(socketServer.RemoteEndPoint.ToString(), Encoding.ASCII.GetString(arrServerRecMsg, 0, length)); break; case "Hexadecimal": returnvalue.Add(socketServer.RemoteEndPoint.ToString(), BaseUtil.ByteToHexadecimalString(arrServerRecMsg, length)); break; default: break; } } } } catch (Exception) { if (socketServer.RemoteEndPoint != null) { } if (list.Contains(socketServer)) { list.Remove(socketServer); } //关闭之前accept出来的和客户端进行通信的套接字 socketServer.Close(); break; } } receiveData = true; 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; } } }