How to set test TCP connection timeout?

前端 未结 3 1427
梦毁少年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.

提交回复
热议问题