6

我正在尝试异步扫描 TCP 端口。由于打开的端口只需要百分之几毫秒即可完成,所以它们很好,但是当端口关闭时,我必须等待响应。

所以发生的事情是我运行应用程序,几乎立刻我看到端口 80 是打开的。然后我必须等待半分钟才能扫描所有其他端口。

编辑。另外,我想在发生时显示响应,而无需等待检查其他端口。

如何使这更快?

private void btnStart_Click(object sender, EventArgs e)
{
    for (int port = 79; port < 90; port++)
    {
        ScanPort(port);
    }
}

private void ScanPort(int port)
{
    TcpClient client = new TcpClient();
    client.BeginConnect(IPAddress.Parse("74.125.226.84"), port, new AsyncCallback(CallBack), client);
}

private void CallBack(IAsyncResult result)
{
    bool connected = false;

    using (TcpClient client = (TcpClient)result.AsyncState)
    {
        try
        {
            client.EndConnect(result);
            connected = client.Connected;
        }
        catch (SocketException)
        {
        }
    }

    if (connected)
    {
        this.Invoke((MethodInvoker)delegate
        {
            txtDisplay.Text += "open2" + Environment.NewLine;
        });
    }
    else
    {
        this.Invoke((MethodInvoker)delegate
        {
            txtDisplay.Text += "closed2" + Environment.NewLine;
        });
    } 
}
4

1 回答 1

8

您可以使用 WaitHandle BeginConnect 返回只等待这么长时间。

using (var tcp = new TcpClient())
{
    var ar = tcp.BeginConnect(host, port, null, null);
    using (ar.AsyncWaitHandle)
    {
        //Wait 2 seconds for connection.
        if (ar.AsyncWaitHandle.WaitOne(2000, false))
        {
            try
            {
                tcp.EndConnect(ar);
                //Connect was successful.
            }
            catch
            {
                //EndConnect threw an exception.
                //Most likely means the server refused the connection.
            }
        }
        else
        {
            //Connection timed out.
        }
    }
}
于 2012-01-26T21:04:08.590 回答