I have a c# application that I use a custom FTP library for. Right now Im using Socket.Send to send the data but I was wondering if it would be better to initiate a NetworkStream with the socket and use NetworkStream.Write instead.
Are there any advantages to using one over the other?
The advantage of a NetworkStream
derives primarily from the fact that it is a Stream
. The disadvantage of a Socket
is that common code that reads and writes from abstract I/O sources like a Stream
cannot handle a Socket
.
The main use case for a NetworkStream
is that you have some code elsewhere that reads or writes from a Stream
, and you wish you could use it with a Socket
. You would know if were in this situation and then NetworkStream
would be a big help!
Say for example you had a communications library and you supported serializing messages from files, named pipes and TCP/IP. The ideal choice for the I/O class would be Stream
. Then your serialization methods could accept a FileStream
, a PipeStream
, or a NetworkStream
. It would even accept a MemoryStream
. This is the benefit of abstraction because after we've created the stream, a method can interact with it without knowing what kind of stream it is.
In this sense, a NetworkStream
uses the adapter design pattern. It adapts the Socket
API to the Stream
API so that clients that are expecting a Stream
can use it.
So finally, the question, if NetworkStream
is a Stream
adapter for a Socket
, which one should we use? Well, if you need a Stream
, then NetworkStream
is your only choice. If you don't need a Stream
, then you can use whichever API you are most comfortable with. If you are already using Socket
successfully, there is no pressing reason to switch to NetworkStream
.
You can potentially separate creation of NetworkStream
and to work with that as with abstract Stream
- so you'll be able to change your transport or simply to create Stream
stubs for testing.
As a question of method itself - NetworkStream.Write
inside has the only operation (except state checks) streamSocket.Send(buffer, offset, size, SocketFlags.None);
- so it's mostly the same as to call that on socket.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With