TCPClient vs Socket in C#

C#.NetSocketsNetwork Programming

C# Problem Overview


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?

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.

C# Solutions


Solution 1 - C#

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.

Update: Since this answer was posted the .Net source code has become available. It does indeed show that TcpClient is a very light wrapper over the Socket class which is itself a wrapper on top of the native WinSock2 API*.

  • On Windows. Will be different for .Net Standard/Core etc. on other platforms.

Solution 2 - C#

Also, you can access the socket directly from the TCPClient object, it's under the property Client - so there is no performance difference.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSashaView Question on Stackoverflow
Solution 1 - C#sipsorceryView Answer on Stackoverflow
Solution 2 - C#John RaschView Answer on Stackoverflow