如何设置测试TCP连接超时?

Pri*_*ief 13 .net c# connection tcp settimeout

我尝试使用以下代码测试TCP连接.

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

如果IP或端口无效,如何设置超时?

Sai*_*bal 15

没有内置的方法来做到这一点.我在许多应用程序中使用以下代码.代码绝不是原创的,但可以正常运行.请注意,您可能必须向此函数添加重试...有时即使服务器启动并运行它也会返回false.

  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();
        }
    }
Run Code Online (Sandbox Code Playgroud)


Dan*_*han 10

没有直接的方法来实现它,但一种方法是使用一个单独的方法来测试连接.

 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;
            }
        }
Run Code Online (Sandbox Code Playgroud)

此方法将使用WaitHandle等待指定的时间段来建立连接,如果它及时连接,它将关闭连接并返回true,否则,它将超时并返回false.


Cur*_*ore 9

对OP来说太晚了,但是对于仍然从搜索中找到这个页面的其他人来说,你可以使用.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
}
Run Code Online (Sandbox Code Playgroud)