How to set test TCP connection timeout?

前端 未结 3 1425
梦毁少年i
梦毁少年i 2020-12-31 08:16

I try to test TCP connection with the following code.

System.Threading.Thread t = new System.Threading.Thread(() =>
{      
    using (TcpClient client =          


        
相关标签:
3条回答
  • 2020-12-31 09:06

    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.

    0 讨论(0)
  • 2020-12-31 09:15

    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
    }
    
    0 讨论(0)
  • 2020-12-31 09:21

    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();
            }
        }
    
    0 讨论(0)
提交回复
热议问题