How to set test TCP connection timeout?
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 开发者_JS百科time out if the IP or port is invalid?
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();
}
}
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.
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
}
精彩评论