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

查看:31
本文介绍了通过 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"之类的)
  • 客户端通过 TCP 发送 byte[]
  • 服务器接收并输出使用相同编码重新转换的字符串(到列表框)

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

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

Edit-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.

推荐答案

我认为回答问题永远不会太晚,希望有人能在这里找到答案.

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天全站免登陆