I'm playing around making a TCP client/server application using C# and I am confused on what's better to use between these two style in sending messages through the network.
The first style I encountered is converting the message to a byte array and writing it to the NetworkStream of an instance of a TcpClient using NetworkStream.Write(*)
method.
void StyleOne(string msg)
{
TcpClient client = new TcpClient();
client.Connect(ip, port);
NetworkStream nwStream = client.GetStream();
byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(msg);
nwStream.Write(bytesToSend, 0, bytesToSend.Length);
nwStream.Flush();
client.Close();
}
Another style I encountered is passing the NetworkStream of the TcpClient instance to a StreamWriter and then using the StreamWriter.Write()
method to write the message to the stream
void StyleTwo(string msg)
{
TcpClient client = New TcpClient(ip, port);
StreamWriter writer = New StreamWriter(client.GetStream());
writer.Write(msg);
writer.Flush();
client.Close();
}
Which of these two is more efficient in terms of Memory, Speed, and Performance if messages that will be sent through the network would at most a megabyte large?
A StreamWriter
instance always uses the same encoding (which you can specify in its constructor), and has some convenience methods to write different types of data to the stream.
In your first example, you more or less do exactly what a StreamWriter
would do under the hood: apply the encoding and write data to the underlying stream.
If you have to send multiple bits of data (in the same encoding), using the StreamWriter
would result in alot cleaner code. For just a single string
I don't think it really matters which approach you take.