如何设置测试 TCP 连接超时? [英] How to set test TCP connection timeout?

查看:56
本文介绍了如何设置测试 TCP 连接超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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();

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

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

推荐答案

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

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();
        }
    }

这篇关于如何设置测试 TCP 连接超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆