How to set test TCP connection timeout?(如何设置测试 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 连接超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何设置测试 TCP 连接超时?
基础教程推荐
- 如何激活MC67中的红灯 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- rabbitmq 的 REST API 2022-01-01