SlowForce
SlowForce

Reputation: 31

Should I use StreamReader/Writer with NetworkStream for C# server/client?

I'm in the process of building a client/server based game for a project(feeling quite out my depth). I've been using TCPclient and a multi-threaded socket server. Everything is working fine at the moment but I have been using StreamReader and StreamWriter to communicate between both client and server.

I keep seeing examples like this for recieving data:

byte[] data = new byte[1024];
int recv = sock.ReceiveFrom(data, ref ep);
string stringData = Encoding.ASCII.GetString(data, 0, recv);

and this for sending:

byte[] data = Encoding.ASCII.GetBytes("This is a test message");
server.SendTo(data, iep);

I was wondering what are the benefits of using this over streamReader? Would using this also be buffering?

Thanks in advance.

Upvotes: 3

Views: 2797

Answers (2)

Mohammad Ayub Latif
Mohammad Ayub Latif

Reputation: 1

sendTo() and receiveFrom() are used for connection less sockets, that use UDP as the transport protocol. You can use Send() or Recieve() when using connection oriented or stream sockets that use TCP as the protocol.
StreamReader and StreamWriter are the classes of IO namespace that will help in solving the message boundary problem that come with TCP sockets.
Message boundary problem means that all send calls are not picked up in all receive calls.
To avoid the message boundary problem we use networkstream with streamreader and streamwriter.

Upvotes: 0

John Saunders
John Saunders

Reputation: 161773

It's just a different style. ReceiveFrom and SendTo are more Unix-style, and using a StreamReader is more of a .NET style. StreamReader would be of more use to you, as you could then pass it to other methods that accept a TextReader.

Upvotes: 3

Related Questions