How to set test TCP connection timeout?

2020-02-26 06:42发布

问题:

I try to test TCP connection with the following code.

System.Threading.Thread t = new System.Threading.Thread(() =>
{      
    using (TcpClient client = new TcpClient())
    {
        client.Connect(ip, Convert.ToInt32(port));
    }
});
t.Start();

How to set time out if the IP or port is invalid?

回答1:

There is no built in way to do this. I use the following code for many of our application. The code is by no means original but works out okay. Please note that you may have to add retries to this function... sometimes it returns false even when the server is up and running.

  private static bool _TryPing(string strIpAddress, int intPort, int nTimeoutMsec)
    {
        Socket socket = null;
        try
        {
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, false);


            IAsyncResult result = socket.BeginConnect(strIpAddress, intPort, null, null);
            bool success = result.AsyncWaitHandle.WaitOne(nTimeoutMsec, true);

            return socket.Connected;
        }
        catch
        {
            return false;
        }
        finally
        {
            if (null != socket)
                socket.Close();
        }
    }


回答2:

There is no direct way to achieve it, but one way to do it can be to have a seperate method which would test the connection.

 static bool TestConnection(string ipAddress, int Port, TimeSpan waitTimeSpan)
        {
            using (TcpClient tcpClient = new TcpClient())
            {
                IAsyncResult result = tcpClient.BeginConnect(ipAddress, Port, null, null);
                WaitHandle timeoutHandler = result.AsyncWaitHandle;
                try
                {
                    if (!result.AsyncWaitHandle.WaitOne(waitTimeSpan, false))
                    {
                        tcpClient.Close();
                        return false;
                    }

                    tcpClient.EndConnect(result);
                }
                catch (Exception ex)
                {
                    return false;
                }
                finally
                {
                    timeoutHandler.Close();
                }
                return true;
            }
        }

This method would use a WaitHandle that would wait for the specified time period to get the connection established, if it gets connected in time, it would close the connection and return true, else, it would timeout and return false.



回答3:

Much too late to be of use to the OP but for anybody else still finding this page from a search, you can solve this using the asynchronous programming features introduced in .Net 4.5.

var hostname = "127.0.0.1";
var port = 123;
var timeout = TimeSpan.FromSeconds(3);
var client = new TcpClient();
if (!client.ConnectAsync(hostname, port).Wait(timeout))
{
    // timed out
}