68

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.

Luke Girvin
  • 13,221
  • 9
  • 64
  • 84

2 Answers2

58

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.
sipsorcery
  • 30,273
  • 24
  • 104
  • 155
  • 2
    'style' is a big word for 'common sense' here. If you can use a prefab, by all means, do so :) – xtofl Jun 05 '11 at 18:20
  • 7
    The note here seems to contradict this. http://msdn.microsoft.com/en-us/library/system.net.sockets.socket%28v=vs.110%29.aspx "If you are writing a relatively simple application and _do not require maximum performance_, consider using TcpClient" – Jon Jan 09 '14 at 00:45
  • 4
    There is no contradiction. The general assumption about a higher-level of abstraction is that it is less flexible with regard to the underlying functionality. Hence, if you need to do something that does not fit the model of say, `TcpClient`, you might end up twisting and bending its API and lose in readability and performance in the process. If you're using it for what it's designed to do however there is no inherent reason to believe that it will perform less well than a more explicit API, yet you will gain in readability. – tne Jan 17 '15 at 03:16
18

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

John Rasch
  • 62,489
  • 19
  • 106
  • 139