如何设置测试 TCP 连接超时?

编程入门 行业动态 更新时间:2024-10-28 07:34:47
本文介绍了如何设置测试 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 连接超时?

本文发布于:2023-10-16 06:15:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1496732.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何设置   测试   TCP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!