簡體   English   中英

通過TcpClient(byte [])發送包含特殊字符的字符串

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

我正在嘗試通過TcpClient(byte [])發送包含特殊字符的字符串。 這是一個例子:

  • 客戶在文本框中輸入“amé”
  • 客戶端使用特定編碼將字符串轉換為byte [] (我已經嘗試了所有預定義的加上一些像“iso-8859-1”)
  • 客戶端通過TCP發送byte []
  • 服務器接收並輸出使用相同編碼重新轉換的字符串(到列表框)

編輯:

我忘了提到結果字符串是“我?”。

編輯-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("ééé"); 奇跡般有效。

我想回答一個問題永遠不會太晚,希望有人能在這里找到答案。

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

你的問題似乎是Encoding.ASCII.GetBytes("amé"); Encoding.ASCII.GetString(buffer); 電話,正如他的評論中的“500 - 內部服務器錯誤”暗示的那樣。

é字符是一個多字節字符,以UTF-8編碼,字節序列為C3 A9 當您使用Encoding.ASCII類進行編碼和解碼時, é字符將轉換為問號,因為它沒有直接的ASCII編碼。 對於在ASCII中沒有直接編碼的任何字符都是如此。

更改您的代碼以使用Encoding.UTF8.GetBytes()Encoding.UTF8.GetString() ,它應該適合您。

您的問題和錯誤對我來說並不清楚,但使用Base64String可能會解決問題
像這樣的東西

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM