Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TcpClient.GetStream().Read() vs. TcpClient.Client.Receive()

Tags:

c#

.net

sockets

.NET allows two very similar ways to "read" from the network (assuming TCP connection):

1. TcpClient.GetStream().Read() 
2. TcpClient.Client.Receive()

By looking at NetworkStream source code - it seems that it's an extra wrapper over the underlying socket, which eventually calls Socket methods.

Question: what's the benefit of using "indirect" NetworkStream variation (#1), instead of using direct wrapper provided by Socket implementation?

Thank you, Boris.

like image 544
Borka Avatar asked Nov 16 '09 18:11

Borka


1 Answers

There is, in fact, a pretty clear benefit of using the first option (TcpStream and not Socket). The benefit is that stream API is more flexible when different underlying implementations are needed at for the same program.

For example, a code which sometimes may use SSL and sometimes may not use it, can switch between SslStream and TcpStream with no changes to the calling code. This is something which is much harder to accomplish using only plain Socket API.

like image 140
Borka Avatar answered Nov 04 '22 05:11

Borka