C# 中的 TCPClient 与 Socket
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/685995/
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
TCPClient vs Socket in C#
提问by
I don't see much use of TCPClient
, yet there is a lot of Socket
? What is the major difference between them and when would you use each?
我没有看到很多用途TCPClient
,但有很多Socket
? 它们之间的主要区别是什么?您何时会使用它们?
I understand that .NET Socket
is written on top of WINSOCK, and TCPClient
is a wrapper over Socket
class. Thus TCPClient
is way up the chain, and possibly inefficient. Correct me if I am wrong.
我知道 .NETSocket
是在 WINSOCK 之上编写的,并且TCPClient
是Socket
类的包装器。因此TCPClient
是链上的方式,并且可能效率低下。如果我错了,请纠正我。
采纳答案by sipwiz
The use of TcpClient and TcpListener just means a few less lines of code. As you say it's just a wrapper over the Socket class so there is no performance difference between them it's purely a style choice.
使用 TcpClient 和 TcpListener 只是意味着少了几行代码。正如您所说,它只是 Socket 类的包装器,因此它们之间没有性能差异,这纯粹是一种风格选择。
Update:Since this answer was posted the .Net source code has become available. It does indeed show that TcpClientis a very light wrapper over the Socketclass which is itself a wrapper on top of the native WinSock2 API*.
更新:自从发布此答案后,.Net 源代码已可用。它确实表明TcpClient是Socket类的一个非常轻量级的包装器,它本身就是原生WinSock2 API*之上的一个包装器。
- On Windows. Will be different for .Net Standard/Core etc. on other platforms.
- 在 Windows 上。其他平台上的 .Net Standard/Core 等会有所不同。
回答by John Rasch
Also, you can access the socket directly from the TCPClient
object, it's under the property Client
- so there is no performance difference.
此外,您可以直接从TCPClient
对象访问套接字,它位于属性下Client
- 因此没有性能差异。