123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314 |
- 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<string, string> returnvalue = new Dictionary<string, string>();
- 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<string, string> Returnvalue
- {
- get
- {
- return returnvalue;
- }
- set
- {
- returnvalue = value;
- }
- }
- public Dictionary<string, string> ReceiveCoding = new Dictionary<string, string>();
- private string iP;
- private string port;
- public List<Socket> list = new List<Socket>();
- 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;
- }
- }
- }
|