What is the difference between NetworkStream and Socket classes?

I have a project where I could abstract the connection between the client and the server. I originally used Sockets and TCP. Then I thought that it would be nice to be able to switch to the communication channel between the processes. Then I looked at the System.IO.PipedStream class and saw that there were many overlaps between the PipeStream and Socket class. But when I looked at the Socket class, it inherits from Object. Thus, there is no single interface or abstract class between Socket and PipeStreams.

Then I remembered something about NetworkStream. This is apparently a shell of the Socket class. But at least NetworkStream and PipeStream inherit from Stream. This means that I can change my implementation. I think I have not tried it yet. I use sockets all the time.

So my question is: is there a drawback in using the NetworkStream class over the Socket class. Any errors or something that you can pay attention to?

+4
source share
2 answers

If you are forced to use low-level parameters, such as sockets and channels, and want an abstraction to pull streaming data from these data sources, Stream is ideal because it provides this abstraction for this model.

If you are encoding Stream instances, then you can implement Stream something, rather than worry about the underlying transport.

Regarding the use of NetworkStream and Socket, NetworkStream simply wraps an instance of Socket and applies calls to the pull (Stream) model to Socket.

+1
source

Since you are not aware of any flaws when switching from Socket to NetworkStream , you most likely will not need to use Socket directly. Socket gives you much more control, but since you are not aware of these shortcomings, you most likely will not need this control.

Just remember that things don't get reliable or fast because you are switching to NetworkStream . (It's easy to forget when you start switching between different stream implementations).

+1
source

All Articles