我正在尝试通过TcpClient(byte [])发送包含特殊字符的字符串。 这是一个例子:
客户在文本框中输入“amé” 客户端使用特定编码将字符串转换为byte [] (我已经尝试了所有预定义的加上一些像“iso-8859-1”) 客户端通过TCP发送字节[] 服务器接收并输出使用相同编码重新转换的字符串(到列表框)编辑:
我忘了提到结果字符串是“我?”。
编辑2(按要求,这里是一些代码):
@DJKRAZE这里有一些代码:
byte[] buffer = Encoding.ASCII.GetBytes("amé"); (TcpClient)server.Client.Send(buffer);在服务器端:
byte[] buffer = new byte[1024]; Client.Recieve(buffer); string message = Encoding.ASCII.GetString(buffer); ListBox1.Items.Add(message);出现在列表框中的字符串是“am?”
===解决方案===
Encoding encoding = Encoding.GetEncoding("iso-8859-1"); byte[] message = encoding.GetBytes("babé");更新:
只需使用Encoding.Utf8.GetBytes("ééé"); 奇迹般有效。
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 converts string to byte[] using a certain encoding (I've tried all the predefined ones plus some like "iso-8859-1") Client sends byte[] through TCP Server receives and outputs the string reconverted with the same encoding (to a listbox)Edit :
I forgot to mention that the resulting string was "am?".
Edit-2 (as requested, here's some code):
@DJKRAZE here's a bit of 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 string that appears in the listbox is "am?"
=== Solution ===
Encoding encoding = Encoding.GetEncoding("iso-8859-1"); byte[] message = encoding.GetBytes("babé");Update:
Simply using Encoding.Utf8.GetBytes("ééé"); works like a charm.
最满意答案
不要太迟回答我认为的问题,希望有人能在这里找到答案。
C#使用16位字符,ASCII将它们截断为8位,以适合一个字节。 经过一番研究,我发现UTF-8是特殊字符的最佳编码。
//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);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);更多推荐
发布评论