user3772253
user3772253

Reputation: 53

Add header to server/client connection

I am needing to translate this code to add a big endian 2 byte header. It works now without header but I am a little lost on how to add it.

TcpClient client = new TcpClient(ipNum, portNum);
NetworkStream nw = client.GetStream();
byte[] send = Encoding.UTF8.GetBytes(userInput);

Console.WriteLine("Sending : " + userInput);
nw.Write(send, 0, send.Length);

byte[] readBytes = new byte[client.ReceiveBufferSize];
int bytesRead = nw.Read(readBytes, 0, client.ReceiveBufferSize);
Console.WriteLine("Received : " + Encoding.UTF8.GetString(readBytes 0, readBytes);

Upvotes: 0

Views: 1046

Answers (1)

usr
usr

Reputation: 171246

UTF8Encoding supports adding that header. Instantiate that class manually and use the constructor that allows you to specify that you want a BOM header.

Note, that your read code is broken because you might receive less than one "message" from the remote side. You might receive just one byte at a time. client.ReceiveBufferSize also makes no sense. Just choose a static buffer size such as 4096.

Upvotes: 1

Related Questions