Sending a string containing special characters through a TcpClient (byte[])

后端 未结 3 1044
轻奢々
轻奢々 2021-01-05 01:54

I\'m trying to send a string containing special characters through a TcpClient (byte[]). Here\'s an example:

  • Client enters \"amé\" in a textbox
  • Client
3条回答
  •  萌比男神i
    2021-01-05 02:25

    Never too late to answer a question I think, hope someone will find answers here.

    C# uses 16 bit chars, and ASCII truncates them to 8 bit, to fit in a byte. After some research, I found UTF-8 to be the best encoding for special characters.

    //data to send via TCP or any stream/file
    byte[] string_to_send = UTF8Encoding.UTF8.GetBytes("amé");
    
    //when receiving, pass the array in this to get the string back
    string received_string = UTF8Encoding.UTF8.GetString(message_to_send);
    

提交回复
热议问题