C# 关闭和清理 Socket 连接的正确方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15354946/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:29:44  来源:igfitidea点击:

What is the proper way of closing and cleaning up a Socket connection?

c#socketsnetworking

提问by AngryHacker

I am a bit confused by the cornucopia of related methods on the Socket object that supposedly close and clean up a socket connection. Consider the following:

我对 Socket 对象上的相关方法的聚宝盆感到有些困惑,这些方法据称可以关闭和清理套接字连接。考虑以下:

var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect("192.168.1.22", 8333);
socket.Send(Encoding.UTF8.GetBytes("hello"));

// now for the closing fun
socket.Shutdown(SocketShutdown.Both);
socket.Disconnect(false);
socket.Close();
socket.Dispose();

In addition, this guysays that to really cleanly close a connection, one must execute socket.Shutdown(SocketShudown.Send), then wait for the other side to respond.

另外,这家伙说要真正彻底关闭连接,必须先执行socket.Shutdown(SocketShudown.Send),然后等待对方响应。

What is the correct way to close, then clean up a socket connection?

关闭然后清理套接字连接的正确方法是什么?

采纳答案by Nikita B

Closing socket closes the connection, and Close is a wrapper-method around Dispose, so generally

Closing socket关闭连接,Close是Dispose的封装方法,所以一般

socket.Shutdown(SocketShutdown.Both);
socket.Close();

should be enough. Some might argue, that Close implementation might change one day (so it no longer calls Dispose), and you should call Dispose manually after calling Close, but i doubt thats gonna happen, personally :)

应该够了。有些人可能会争辩说,Close 的实现有一天可能会改变(因此它不再调用 Dispose),您应该在调用 Close 后手动调用 Dispose,但我个人怀疑这会发生:)

Alternatively, consider using using (yeh):

或者,考虑使用 using (yeh):

using (var socket = new Socket(...))
{
    ....
    socket.Shutdown(SocketShutdown.Both);
}