21

I understand that a TcpClient is a wrapper around the socket class, and I can access the underlying socket if using the TcpClient, but what exactly does the wrapper do?

When using the TCPClient do i need to keep calling Receive() like I do with a socket or does the wrapper ensure all my data appears?

Lastly, can I use the TcpClient on both the server and the client to wrap the socket (after using TcpListener to accept the original connection on the server)

Dermot
  • 1,713
  • 2
  • 18
  • 29

1 Answers1

22

what exactly does the wrapper do?

Let me explain this with an example. You have a method in C# File.ReadAllLines. It reads all lines in the file for you. Now you can also achieve same results via FileStream class or any other class which reads file .. BUT.. wrapper i.e. File.ReadAllLines, allows you to achieve the same with less lines of code. Wrappers always increase productivity by abstracting out the low level details

When using the TCPClient do i need to keep calling Receive() like I do with a socket or does the wrapper ensure all my data appears?

TCPClient don't have a Receive method like Socket but the idea is same. You will have to use methods like GetStream to read the data it won't automagically appear for you

Can I use the TcpClient on both the server and the client to wrap the socket

Yes, you can safely use it on both client and server side

Haris Hasan
  • 29,856
  • 10
  • 92
  • 122
  • Ah I see. So am I right in saying that equivalent of performing _BeginReceive(), followed by EndReceive(), store bytes and recall BeginReceive() again until message received_ on a socket, can be performed by using _myTcpClient.GetStream().BeginRead()_ on a TcpClient? Will BeginRead() not call the EndRead() callback until the specified number of bytes received has indeed been received? (removing the need to constantly call BeginRead()/BeginReceive() until all expected bytes have been received) – Dermot Mar 04 '12 at 09:17
  • 1
    I would prefer to use `Read` and `Write` methods of `NetworkStream` class instead of `BeginRead` and `EndRead` because you won't have to explicitly call `BeginRead` and `EndRead` the wrapper would do it for you. See some samples on internet like this one http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.getstream.aspx – Haris Hasan Mar 04 '12 at 10:22