如何配置socket连接超时
当客户端尝试连接到已断开连接的 IP 地址时,会出现超过 15 秒的长时间超时...我们如何减少此超时? 配置方法是什么?
我用来设置套接字连接的代码如下:
try
{
m_clientSocket = new Socket(
AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
IPAddress ip = IPAddress.Parse(serverIp);
int iPortNo = System.Convert.ToInt16(serverPort);
IPEndPoint ipEnd = new IPEndPoint(ip, iPortNo);
m_clientSocket.Connect(ipEnd);
if (m_clientSocket.Connected)
{
lb_connectStatus.Text = "Connection Established";
WaitForServerData();
}
}
catch (SocketException se)
{
lb_connectStatus.Text = "Connection Failed";
MessageBox.Show(se.Message);
}
When the Client tries to connect to a disconnected IP address, there is a long timeout over 15 seconds... How can we reduce this timeout? What is the method to configure it?
The code I'm using to set up a socket connection is as following:
try
{
m_clientSocket = new Socket(
AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
IPAddress ip = IPAddress.Parse(serverIp);
int iPortNo = System.Convert.ToInt16(serverPort);
IPEndPoint ipEnd = new IPEndPoint(ip, iPortNo);
m_clientSocket.Connect(ipEnd);
if (m_clientSocket.Connected)
{
lb_connectStatus.Text = "Connection Established";
WaitForServerData();
}
}
catch (SocketException se)
{
lb_connectStatus.Text = "Connection Failed";
MessageBox.Show(se.Message);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(12)
Socket 类中应该有一个 ReceiveTimeout 属性。
Socket.ReceiveTimeout 属性
There should be a ReceiveTimeout property in the Socket class.
Socket.ReceiveTimeout Property
我找到了这个。 比接受的答案更简单,并且适用于 .NET Framework v2
I found this. Simpler than the accepted answer, and works with .NET Framework v2
我的看法:
My take:
我刚刚编写了一个扩展类,以便允许连接超时。 使用它与使用标准
Connect()
方法完全一样,并带有一个名为timeout
的额外参数。I just wrote an extension class in order to allow timeouts in connections. Use it exactly as you would use the standard
Connect()
methods, with an extra parameter namedtimeout
.可能为时已晚,但有一个基于 Task.WaitAny (c# 5 +) 的简洁解决方案:
it might be too late but there is neat solution based on Task.WaitAny (c# 5 +) :
我不会用 C# 编程,但在 C 中,我们通过使套接字成为非阻塞,然后将 fd 放入 select/poll 循环中来解决相同的问题,超时值等于我们愿意等待连接的时间量成功。
我找到了 Visual C++ 的 this ,那里的解释也倾向于选择/poll 机制我之前解释过。
根据我的经验,您无法更改每个套接字的连接超时值。 您可以更改所有内容(通过调整操作系统参数)。
I dont program in C# but in C, we solve the same problem by making the socket non-blocking and then putting the fd in a select/poll loop with a timeout value equal to the amount of time we are willing to wait for the connect to succeed.
I found this for Visual C++ and the explanation there also bends towards the select/poll mechanism I explained before.
In my experience, you cannot change connect timeout values per socket. You change it for all (by tuning OS parameters).
我通过使用 Socket.ConnectAsync 方法而不是 Socket.Connect 方法解决了该问题。
调用Socket.ConnectAsync(SocketAsyncEventArgs)后,启动一个定时器(timer_connection),如果时间到了,检查socket连接是否已连接(if(m_clientSocket.Connected)),如果没有,则弹出超时错误。
I solved the problem by using Socket.ConnectAsync Method instead of Socket.Connect Method.
After invoking the Socket.ConnectAsync(SocketAsyncEventArgs), start a timer (timer_connection), if time is up, check whether socket connection is connected (if(m_clientSocket.Connected)), if not, pop up timeout error.
请在 MSDN 上查看。 您似乎无法使用 Socket 类中实现的属性来执行此操作。
MSDN 上的海报实际上解决了他的问题使用线程的问题。 他有一个主线程,它调用其他线程运行连接代码几秒钟,然后检查套接字的 Connected 属性:
您想做什么,为什么不能在超时之前等待 15-30 秒?
Check this out on MSDN. It does not appear that you can do this with the implemented properties in the Socket class.
The poster on MSDN actually solved his problem using threading. He had a main thread which called out to other threads which run the connection code for a couple seconds and then check the Connected property of the socket:
What are you trying to do, and why can't it wait for 15-30 seconds before timing out?
连接到套接字时我遇到了同样的问题,我想出了以下解决方案,它对我来说效果很好。
`
I had the Same problem when connecting to a Socket and I came up with the below solution ,It works Fine for me.
`
我使用 Unity 时遇到了 BeginConnect 和来自套接字的其他异步方法的一些问题。
有些东西我不明白,但之前的代码示例对我不起作用。
所以我写了这段代码来让它工作。 我在带有 android 和 pc 的 adhoc 网络上测试它,也在我的计算机上进行本地测试。 希望它能有所帮助。
C# 上有一个非常简单的看门狗可以让它工作:
I worked with Unity and had some problem with the BeginConnect and other async methods from socket.
There is something than I don't understand but the code samples before doesn't work for me.
So I wrote this piece of code to make it work. I test it on an adhoc network with android and pc, also in local on my computer. Hope it can help.
and there a very simple watchdog on C# to make it work:
这就像 FlappySock 的答案,但我添加了一个回调,因为我不喜欢布局以及布尔值的返回方式。 在尼克·米勒对该答案的评论中:
所以对我来说,似乎依赖于什么返回可能很危险 - 我更喜欢使用
socket.Connected
。 我设置了一个可为空的布尔值并在回调函数中更新它。 我还发现它并不总是在返回主函数之前完成报告结果 - 我也处理这个问题,并使用超时让它等待结果:相关: 如何检查我是否已连接?
This is like FlappySock's answer, but I added a callback to it because I didn't like the layout and how the Boolean was getting returned. In the comments of that answer from Nick Miller:
So to me, it seems relying on what is returned can be dangerous - I prefer to use
socket.Connected
. I set a nullable Boolean and update it in the callback function. I also found it doesn't always finish reporting the result before returning to the main function - I handle for that, too, and make it wait for the result using the timeout:Related: How to check if I'm connected?
我尝试过 dotnet 6,接受连接后 dotnet 允许您设置超时。
并且您必须使用
Receive
进行管理来源:微软
I have tried with dotnet 6, and after accepting a connection dotnet allows you to set the timeout.
and the you have to manage with
Receive
Source: Microsoft