Thursday, April 14, 2011

Networking in C#

Why we need Reader/Writer Streams while Using TCPListner in C# networking?

example :

TcpClient client = server.AcceptTcpClient();
client.ReceiveTimeout = 75000;
Stream s = client.GetStream();
StreamReader reader = new StreamReader(s);
StreamWriter writer = new StreamWriter(s);
writer.AutoFlush = true;
From stackoverflow
  • You don't need them. You can use raw sockets if you don't like the Tcp wrapper classes. Take a look at System.Net.Sockets.

  • The TcpListener is designed to use streams for a couple of reasons.

    First, it makes the API consistent with other, mid-high level (compared to using raw sockets) APIs in the BCL. For example, the standard way of handling File IO is to use Streams.

    Second, streams provide a huge advantage for reading and writing to TCP channels. True, when you are working on very simple cases, they make life slightly, but just slightly, more difficult. However, when you start looking at more complex scenarios, they make everything much simpler.

    For example, if the Tcp API didn't use streams, it would be much more difficult to do things like compress traffic across the connection (just pass the writer+reader through a GZipStream or similar), or much more difficult to encrypt all of your communication across the wire. Streams provide huge amounts of opportunity to easily extend your algorithm to handle situations that may arise in the future.

  • You only need StreamReader/StreamWriter if you want to deal with text instead of binary data.

    Sockets deal with binary data naturally, which is why TcpClient exposes a Stream. Stream is a binary abstraction, hence its Read/Write methods deal in byte arrays. TextReader/TextWriter (from which StreamReader/StreamWriter are derived) deal with text - their methods deal with strings and char arrays.

    StreamReader/StreamWriter basically wrap a stream and do the conversion (via an Encoding) between text and binary data for you.

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.