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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 13:24:40  来源:igfitidea点击:

TCPClient vs Socket in C#

c#.netsocketsnetwork-programming

提问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 Socketis written on top of WINSOCK, and TCPClientis a wrapper over Socketclass. Thus TCPClientis way up the chain, and possibly inefficient. Correct me if I am wrong.

我知道 .NETSocket是在 WINSOCK 之上编写的,并且TCPClientSocket类的包装器。因此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 源代码已可用。它确实表明TcpClientSocket类的一个非常轻量级的包装器,它本身就是原生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 TCPClientobject, it's under the property Client- so there is no performance difference.

此外,您可以直接从TCPClient对象访问套接字,它位于属性下Client- 因此没有性能差异。