Socket.Close并没有真正关闭TCP套接字? (C#) [英] Socket.Close doesn't really close tcp socket? (c#)
问题描述
似乎使用socket.Close()对于TCP套接字,并没有完全关闭套接字。在下面的例子我想在端口9999,这是不打开连接到example.com,和短超时后,我试图关闭套接字。
It seems that using socket.Close() for a tcp socket, doesn't fully close the socket. In the following example I'm trying to connect to example.com at port 9999, which is not opened, and after a short-timeout, I'm trying to close the socket.
for (int i = 0; i < 200; i++)
{
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.LingerState = new LingerOption(false, 0);
sock.BeginConnect("www.example.com", 9999, OnSocketConnected, sock);
System.Threading.Thread.Sleep(50);
sock.Close();
}
但是,当我看看netstat的循环完成后,我发现,有许多半开的插座:
But when I take a look at netstat after the loop completes, I find that there are many half-opened sockets:
TCP israel-xp:6506 www.example.com:9999 SYN_SENT
TCP israel-xp:6507 www.example.com:9999 SYN_SENT
TCP israel-xp:6508 www.example.com:9999 SYN_SENT
TCP israel-xp:6509 www.example.com:9999 SYN_SENT
的修改的
。
好,有些情况下失踪了。我使用beginconnect,因为我希望套接字连接失败(9999不打开),在我真正的代码,我调用Socket.close()一次设置计时器。
在OnSocketConnected我打电话EndConnect,它抛出一个异常(试图调用一个释放的对象的方法)。
我的目标是有套接字连接阶段短超时。
EDIT . Ok, some context was missing. I'm using beginconnect because I expect the socket connection to fail (9999 is not opened), and in my real code, I call the socket.Close() once a timer is set. On OnSocketConnected I call EndConnect, which throws an exception (trying to call a method of a disposed object). My goal is having a short timeout for the socket connection stage.
任何线索我在做什么错?
谢谢!
Any clue what I'm doing wrong? Thanks!
推荐答案
这将关闭套接字的.NET一部分。然而根据TCP规范操作系统必须保持插座开了一定量的时间的较低水平花絮以便检测重传,以及类似的。在这种特殊情况下,它可能保持插座周围有点以便检测到发送,因此它可以回答更理智,而不是混淆与发送更多的数据包的答复SYN包的回复。
It will close the .NET part of the socket. However according to the TCP specification the OS have to keep the lower level tidbits of the socket open for a certain amount of time in order to detect retransmission, and similar. In this particular case it's likely keeping the socket around for a bit in order to detect a reply to the SYN packet sent so it can reply more sensibly and not mix up the reply with further packets sent.
这篇关于Socket.Close并没有真正关闭TCP套接字? (C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!