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
NetworkStreamderives primarily from the fact that it is aStream. The disadvantage of aSocketis that common code that reads and writes from abstract I/O sources like aStreamcannot handle aSocket.The main use case for a
NetworkStreamis that you have some code elsewhere that reads or writes from aStream, and you wish you could use it with aSocket. You would know if were in this situation and thenNetworkStreamwould 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 aFileStream, aPipeStream, or aNetworkStream. It would even accept aMemoryStream. 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
NetworkStreamuses the adapter design pattern. It adapts theSocketAPI to theStreamAPI so that clients that are expecting aStreamcan use it.So finally, the question, if
NetworkStreamis aStreamadapter for aSocket, which one should we use? Well, if you need aStream, thenNetworkStreamis your only choice. If you don’t need aStream, then you can use whichever API you are most comfortable with. If you are already usingSocketsuccessfully, there is no pressing reason to switch toNetworkStream.