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

I am trying to send a string containing special characters through TcpClient (byte []). Here is an example:

  • Client enters "amé" in the text box
  • The client converts the string to byte [] using a specific encoding (I tried all the predefined ones, and some like "iso-8859-1")
  • Client sends byte [] over TCP
  • The server receives and displays a string converted with the same encoding (to the list)

Edit:

I forgot to mention that the resulting line was "am?".

Edit-2 (as requested here, here is the code):

@DJKRAZE here is some code:

byte[] buffer = Encoding.ASCII.GetBytes("amé"); (TcpClient)server.Client.Send(buffer); 

On the server side:

 byte[] buffer = new byte[1024]; Client.Recieve(buffer); string message = Encoding.ASCII.GetString(buffer); ListBox1.Items.Add(message); 

The line that appears in the list is "am?"

=== Solution ===

 Encoding encoding = Encoding.GetEncoding("iso-8859-1"); byte[] message = encoding.GetBytes("babé"); 

Update:

Just using Encoding.Utf8.GetBytes("ééé"); works like a charm.

+4
source share
3 answers

It’s never too late to answer a question, I think I hope someone finds the answers here.

C # uses 16-bit characters, and ASCII truncates them to 8 bits to fit in bytes. After some research, I found UTF-8 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); 
+6
source

It seems that your problem is causing Encoding.ASCII.GetBytes("amé"); calls Encoding.ASCII.GetBytes("amé"); and Encoding.ASCII.GetString(buffer); as stated in "500 - Internal Server Error" in his comments.

The é character is a multibyte character that is encoded in UTF-8 with the byte sequence C3 A9 . When you use the Encoding.ASCII class for encoding and decoding, the é character is converted to a question mark because it does not have direct ASCII encoding. This is true for any character that does not have direct encoding in ASCII.

Change your code to use Encoding.UTF8.GetBytes() and Encoding.UTF8.GetString() , and it should work for you.

+4
source

Your question and your error are not clear to me, but using Base64String may solve the problem
Something like that

 static public string EncodeTo64(string toEncode) { byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode); string returnValue = System.Convert.ToBase64String(toEncodeAsBytes); return returnValue; } static public string DecodeFrom64(string encodedData) { byte[] encodedDataAsBytes = System.Convert.FromBase64String(encodedData); string returnValue = System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes); return returnValue; } 
0
source

All Articles