Пример #1
0
        //检测端口的开启状态
        void TestPort()
        {
            try
            {
                button1.Enabled       = false;
                dataGridView1.Enabled = false;

                label1.Text = "正在获取端口开启状态";
                XmPortBLL bll    = new XmPortBLL();
                TcpBLL    tcpbll = new TcpBLL();
                //获取端口绑定的ip地址
                string ip = tcpbll.GetIp();

                List <Task> taskList = new List <Task>();
                TaskFactory factory  = new TaskFactory();

                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    int j = i;
                    taskList.Add(factory.StartNew(() =>
                    {
                        int port = int.Parse(GetPort(j));
                        //测试端口的连接
                        bool res = bll.TestPort(ip, port);
                        //设置checkbox的选中状态
                        SetCheck(j, res);
                    }));
                }

                ////用于等待其他几个检测端口的线程
                taskList.Add(factory.ContinueWhenAll(taskList.ToArray(), arr =>
                {
                    // Show("刷新端口成功");
                    button1.Enabled       = true;
                    dataGridView1.Enabled = true;
                    label1.Text           = "";
                }));
            }
            catch (Exception ex)
            {
                Show("获取端口状态失败");
                FileOperation.WriteAppenFile("获取端口状态失败 " + ex.Message);
            }
        }
Пример #2
0
        public static void StartListening(int port)
        {
            try
            {
                byte[]     bytes         = new Byte[1024];
                TcpBLL     bll           = new TcpBLL();
                string     ip            = bll.GetIp();
                IPAddress  ipAddress     = IPAddress.Parse(ip);
                IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);

                //启动tcp类型的监听
                Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                //绑定指定的额ip地址和端口
                listener.Bind(localEndPoint);
                //最多同时连接100台设备
                listener.Listen(100);
                while (true)
                {
                    allDone.Reset();
                    string info = "启动成功" + localEndPoint.Address.ToString() + ":" + localEndPoint.Port.ToString() + "等待连接...";
                    FileOperation.WriteAppenFile(info);

                    //开启监听
                    listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
                    allDone.WaitOne();
                }
            }
            catch (Exception e)
            {
                string info = e.Message;
                FileOperation.WriteAppenFile("1" + info);
            }

            Console.Read();
        }