使用线程池检查远程PC上的端口

时间:2013-10-02 22:37:52

标签: c#

我需要使用ThreadPool创建一个使用c#(我的类似主题是关于java)检查远程PC上的端口的程序。端口数可以不同。线程数 - 我可以手动设置(我使用5)。

问题是我有错误 A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond XX.XXX.XX.XX:80

这是我完成此任务的代码

private static int BEGIN = 75; //1
private static int END = 100; //65535
private static string host = "microsoft.com";
public static void concurrent()
    {
        ThreadPool.SetMaxThreads(5, 5);
        Stopwatch p = new Stopwatch();
        p.Start();

        for (int i = BEGIN; i <= END; i++)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(check), i);
        }
        p.Stop();
        Console.WriteLine("Time with concurrency {0}", p.Elapsed);
    }

    private static void check(object o)
    {
        Console.WriteLine("Thread {0} checks port {1}", Thread.CurrentThread.GetHashCode(), (int)o);
        Lab1.makeTCP((int)o);
        //Thread.Sleep(1000);
    }

private static void makeTCP(int port)
    {
        IPAddress ipadr = Dns.GetHostAddresses(host)[0];

        try
        {
            Socket sock = new Socket(AddressFamily.InterNetwork, 
                                        SocketType.Stream, 
                                        ProtocolType.Tcp);
            sock.Connect(ipadr, port);
            if (sock.Connected)
                Console.WriteLine("Port {0} is closed", port);
            sock.Close();

            return;
        }
        catch (SocketException exc)
        {
            if (exc.ErrorCode == 10061)
                Console.WriteLine("Port {0} is open", port);
            else Console.WriteLine(exc.Message);
        }
    }

此外,我想了解如何执行此任务所需的时间。 但是我的Stopwatch stop比所有线程更早发生了。如何解决这个问题?

0 个答案:

没有答案