c#/.Net Socket.Shutdown
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/583637/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
c#/.Net Socket.Shutdown
提问by user70567
I recognize this type of question has a long history, but the way I am using this must be the correct '.net way' and yet it does not seem to work.
我承认这类问题有很长的历史,但我使用它的方式必须是正确的“.net 方式”,但它似乎不起作用。
I have a trivial synchronous IP server daemon that does a simple AcceptSocket, do some stuff, socket.send, socket.shutdown, socket.close. My client is another trivial C# app that does URLDownloadToFile.
我有一个简单的同步 IP 服务器守护进程,它做一个简单的 AcceptSocket,做一些事情,socket.send、socket.shutdown、socket.close。我的客户端是另一个执行 URLDownloadToFile 的简单 C# 应用程序。
What happens is that part of the time URLDownloadToFilefails fails with (0x800C0008) .. thinks its download resource failed.
发生的情况是,部分时间 URLDownloadToFilefails 失败并显示 (0x800C0008) .. 认为其下载资源失败。
My server side end sequence is:
我的服务器端结束顺序是:
socket.Shutdown(Both);
socket.Close();
If I change this to
如果我将其更改为
socket.Disconnect();
socket.Close();
(I open the above with sockopt Linger true, timeout 5 secs)
(我用sockopt打开上面的Linger true,超时5秒)
this works great.
这很好用。
Am I missing something on the Shutdown method.. it sounds like the 'magic bullet' MS wants you to use for gracefully doing an exit that will ultimately send any remaining send data.
我是否在关闭方法上遗漏了一些东西..听起来像“魔法子弹”MS希望您优雅地执行退出,最终将发送任何剩余的发送数据。
Grossly, (and this cannot be right) it appears like the close.. kills any async processing that might be in progress from shutdown().
大体上,(这不可能是正确的)它看起来像 close.. 杀死可能从 shutdown() 进行的任何异步处理。
Any ideas?
有任何想法吗?
回答by ShuggyCoUk
Based on Socket.Disconnect
If you need to call Disconnect without first calling Shutdown, you can set the DontLinger Socket option to false and specify a nonzero time-out interval to ensure that data queued for outgoing transmission is sent. Disconnect then blocks until the data is sent or until the specified time-out expires. If you set DontLinger to false and specify a zero time-out interval, Close releases the connection and automatically discards outgoing queued data.
如果您需要在不先调用 Shutdown 的情况下调用 Disconnect,则可以将 DontLinger Socket 选项设置为 false 并指定非零超时间隔,以确保发送排队等待传出传输的数据。断开连接然后阻塞,直到发送数据或直到指定的超时到期。如果将 DontLinger 设置为 false 并指定零超时间隔,则 Close 会释放连接并自动丢弃传出的排队数据。
Suggests the Shutdown is at best unnecessary...
建议关机充其量是不必要的......
回答by ShuggyCoUk
For reusing the socket use:
要重用套接字,请使用:
socket.Shutdown(SocketShutdown.Both);
socket.Disconnect(true);
For force closing use:
对于强制关闭使用:
socket.Shutdown(SocketShutdown.Both);
socket.Close();