Browse Source

添加Open,Close方法,isOpen属性

章政 8 years ago
parent
commit
96f94316f6
1 changed files with 33 additions and 2 deletions
  1. 33 2
      UAS-MES/PublicMethod/ModeBusTCPServer.cs

+ 33 - 2
UAS-MES/PublicMethod/ModeBusTCPServer.cs

@@ -17,21 +17,44 @@ namespace UAS_MES.PublicMethod
         byte[] M502_ON = new byte[] { 0x00, 0x05, 0x11, 0xF6, 0xFF, 0x00, 0x68, 0xE5 };
         byte[] M502_OFF = new byte[] { 0x00, 0x05, 0x11, 0xF6, 0x00, 0x00, 0x29, 0x15 };
 
+        private bool isOpen = false;
+
         Thread threadWatch = null; //负责监听客户端的线程
         Socket socketWatch = null; //负责监听客户端的套接字
         List<Socket> socConnections = new List<Socket>();  //创建一个负责和客户端通信的套接字 
         List<Thread> dictThread = new List<Thread>();
+        string ip = "";
+        string port = "";
+
+        public bool IsOpen
+        {
+            get
+            {
+                return isOpen;
+            }
+
+            set
+            {
+                isOpen = value;
+            }
+        }
 
         public ModeBusTCPServer(string IP, string Port)
+        {
+            ip = IP;
+            port = Port;
+        }
+
+        public void Open()
         {
             try
             {
                 //定义一个套接字用于监听客户端发来的信息  包含3个参数(IP4寻址协议,流式连接,TCP协议)
                 socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                 //服务端发送信息 需要1个IP地址和端口号
-                IPAddress ipaddress = IPAddress.Parse(IP);
+                IPAddress ipaddress = IPAddress.Parse(ip);
                 //将IP地址和端口号绑定到网络节点endpoint上 
-                IPEndPoint endpoint = new IPEndPoint(ipaddress, int.Parse(Port));
+                IPEndPoint endpoint = new IPEndPoint(ipaddress, int.Parse(port));
                 //监听绑定的网络节点
                 socketWatch.Bind(endpoint);
                 //将套接字的监听队列长度限制为20
@@ -42,6 +65,7 @@ namespace UAS_MES.PublicMethod
                 threadWatch.IsBackground = true;
                 //启动线程
                 threadWatch.Start();
+                isOpen = true;
             }
             catch (Exception e)
             {
@@ -65,6 +89,13 @@ namespace UAS_MES.PublicMethod
             }
         }
 
+        public void Close()
+        {
+            threadWatch.Abort();
+            socketWatch.Close();
+            isOpen = false;
+        }
+
         private void ServerRecMsg(object obj)
         {
             Socket soc = obj as Socket;