Reputation: 13440
I have a project where I might want to abstract the communication between client and server. I was initially using Sockets and TCP. I then thought that it might be nice to be able to switch to an inter process communication channel. I then looked at System.IO.PipedStream class and saw that there was a lot of overlap between the PipeStream and the Socket class. But when I had a look at the Socket class it inherits from Object. So there is no common interface or abstract class between Socket and PipeStreams.
I then remembered something about NetworkStream. It apparently wraps a Socket class. But at least both NetworkStream and PipeStream inherit from Stream. Which means I can swap my implementation out. I think, I haven't tried this yet. I have been using sockets all this time.
So my question is: Is there any disadvantage to using the NetworkStream class over the Socket class. Any gotchas or anything to watch out for?
Upvotes: 5
Views: 6313
Reputation: 101192
Since you do not know about any disadvantages when switching from Socket
to NetworkStream
you will most likely not need to use a Socket directly. Socket
gives you a lot more control, but since you are not aware of the disadvantages you will most likely not need that control.
Just remember that things do not become reliable or fast just because you are switching to a NetworkStream
. (Might be easy to forget when you start to switch between different stream implementations).
Upvotes: 1
Reputation: 74560
If you are forced to use low level options such as sockets and pipes, and you want an abstraction for pulling streaming data from those data sources then the Stream class is perfect, as it provides that abstraction for that model.
If you code against Stream instances, then you can have anything implement the Stream, and not worry about the underlying transport.
In reference to using a NetworkStream vs a Socket, a NetworkStream just wraps a Socket instance and applies the calls to the pull model (the Stream) to the Socket.
Upvotes: 2