通过TcpClient(byte [])发送包含特殊字符的字符串 [英] Sending a string containing special characters through a TcpClient (byte[])

查看:736
本文介绍了通过TcpClient(byte [])发送包含特殊字符的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过TcpClient(byte [])发送一个包含特殊字符的字符串。这里有一个例子:

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


  • 客户端在文本框中输入amé

  • 客户端将字符串转换为字节[]使用某种编码方式(我已经尝试了所有预定义的加号,还有一些像iso-8859-1)

  • 客户端发送byte []通过TCP

  • 服务器接收并输出以相同编码重新转换的字符串(到列表框)

  • 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)

编辑:

我忘了提到结果字符串是am?。

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

编辑2 (根据要求,这里有一些代码):

Edit-2 (as requested, here's some code):

@DJKRAZE这里有一些代码:

@DJKRAZE here's a bit of code :

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?

The string that appears in the listbox is "am?"

===解决方案===

=== Solution ===

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

更新:

只需使用 Encoding.Utf8.GetBytes(ééé); 像一个魅力一样。

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

推荐答案

p>从来不迟于回答一个问题我想,希望有人会在这里找到答案。

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

C#使用16位字符,ASCII将其截断为8位,以适应在一个字节。经过一番研究,我发现UTF-8是特殊字符的最佳编码。

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);

这篇关于通过TcpClient(byte [])发送包含特殊字符的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆