0

I am not sure how this is happening, but I have a section of code that can be simplified to the following:

var tcpClient = CreateAndConnect();
var networkStream = tcpClient.GetStream();   
var streamWriter = new StreamWriter( networkStream, Encoding.UTF8 );
var msg = GetMessage(); 

//if i write this msg directly with this code block i will get a successful response
var bytes = Encoding.UTF8.GetBytes( msg );
await networkStream.WriteAsync( bytes, 0, bytes.Length ); 

//if instead i write to the streamwriter and flush it fails
streamWriter.Write( msg  );
streamWriter.Flush();

I have examined the packets that are sent in wireshark, and they are in fact different by 3 bytes. I dont know enough about packets to know what exactly that difference is, although i can say with certainty the complete message is in both.

cubesnyc
  • 995
  • 10
  • 26
  • 1
    3 Bytes? Perhaps 0xEF 0xBB 0xBF? then it's the UTF8-encoded BOM (Byte Order Mark). See also https://stackoverflow.com/questions/5266069/streamwriter-and-utf-8-byte-order-marks – Klaus Gütter Oct 14 '20 at 11:50

1 Answers1

0

As pointed out in the comments, the issue had to do with a Byte Order Mark, which is a 3 byte code prepended to a string to indicate that the encoding is UTF8.

The static encoding class Encoding.UTF8 prepends the byte order mark to a UTF8 string. The fix is to instantiate a new encoding class via new UTF8Encoding() which does not add a byte order mark unless told to explicitly.

cubesnyc
  • 995
  • 10
  • 26