[英]What exactly do socket's Shutdown, Disconnect, Close and Dispose do?
It's surprisingly hard to find a simple explanation on what these four methods actually do, aimed at network programming newbies. 很难找到关于这四种方法实际做什么的简单解释,针对网络编程新手。 People usually just state what they believe is the proper way to close a socket in a particular scenario, but not what happens in the background behind each step.
人们通常只是声明他们认为在特定场景中关闭套接字的正确方法,而不是在每个步骤背后的背景中发生的事情。
Going by the teach-a-man-to-fish philosophy, can you explain the Shutdown
, Disconnect
, Close
and Dispose
methods? 通过教导人与鱼的理念,您能解释
Shutdown
, Disconnect
, Close
和Dispose
方法吗?
An answer on StackOverflow made me think I have finally reached some glimpse of an understanding. StackOverflow的答案让我觉得我终于看到了一些谅解。 Then I went testing for a bit and here's the summary of a newbie's view.
然后我进行了一些测试,这是新手视图的摘要。 Please correct me if I'm wrong because this is based on inference, not expertise.
如果我错了,请纠正我,因为这是基于推理,而不是专业知识。
Shutdown
disables the Send
and/or Receive
methods, depending on the provided argument. Shutdown
禁用Send
和/或Receive
方法,具体取决于提供的参数。 It doesn't disable the underlying protocol handling and it never blocks. 它不会禁用底层协议处理,它永远不会阻塞。
If Send
is disabled, it also queues up a zero-byte send packet into the underlying send buffer. 如果禁用
Send
,它还会将零字节发送数据包排入底层发送缓冲区。 When the other side receives this packet, it knows that your socket will no longer send any data. 当另一方收到此数据包时,它知道您的套接字将不再发送任何数据。
If Receive
is disabled, any data the other side might be trying to send will be lost. 如果禁用
Receive
则另一方可能尝试发送的任何数据都将丢失。
If Receive
is disabled without disabling Send
, it just prevents the socket from receiving data. 如果在未禁用
Send
情况下禁用Receive
,则只会阻止套接字接收数据。 Since no zero-byte packet will be sent, the other side won't know anything about it until it tries to send something, and only if the socket's protocol requires acknowledging. 由于不会发送零字节数据包,因此另一方在尝试发送内容之前不会知道任何事情,并且只有在套接字协议需要确认时才会知道。
First, Disconnect
does the equivalent of Shutdown(SocketShutdown.Both)
. 首先,
Disconnect
相当于Shutdown(SocketShutdown.Both)
。
Then it blocks, waiting for two things: 然后它阻塞,等待两件事:
If you call Disconnect(false)
, system resources will be freed. 如果调用
Disconnect(false)
,系统资源将被释放。
Close
frees system resources. Close
释放系统资源。 May abruptly stop sending queued-up data. 可能会突然停止发送排队的数据。 If called with the argument, will wait for the data to be sent, but only up to the specified timeout.
如果使用参数调用,将等待数据发送,但仅限于指定的超时。
Dispose
is same as the Close
overload without the timeout argument. Dispose
与没有timeout参数的Close
重载相同。 To be more precise, Close
without timeout is the same as Dispose
. 更确切地说,没有超时的
Close
与Dispose
相同。
If you use the using
block on the socket, it will automatically call Dispose
. 如果在套接字上使用
using
块,它将自动调用Dispose
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.