簡體   English   中英

將unicode String從C#發送到Java

[英]Send unicode String from C# to Java

在C#端,我有這個代碼發送unicode String

    byte[] b = System.Text.Encoding.UTF8.GetBytes(str);
    string unicode = System.Text.Encoding.UTF8.GetString(b);
    //Plus \r\n for end of send string
    SendString(unicode + "\r\n");


   void SendString(String message)
    {
        byte[] buffer = Encoding.ASCII.GetBytes(message);
        AsyncCallback ac = new AsyncCallback(SendStreamMsg);
        tcpClient.GetStream().BeginWrite(buffer, 0, buffer.Length, ac, null);
    }

    private void SendStreamMsg(IAsyncResult ar)
    {
        tcpClient.GetStream().EndWrite(ar);
        tcpClient.GetStream().Flush(); //data send back to java
    }

這是Java方面

     Charset utf8 = Charset.forName("UTF-8");
        bufferReader = new BufferedReader(new InputStreamReader(
                sockServer.getInputStream(),utf8));
     String message = br.readLine();

問題是我無法在Java端接收unicode字符串。 怎么解決呢?

您的問題有點模棱兩可; 你說你不能在Java端接收unicode字符串 - 你是收到錯誤,還是得到一個ASCII字符串? 我假設您正在獲取ASCII字符串,因為這是您的SendString()方法發送的,但可能還有其他問題。

您的SendString()方法首先將傳入的字符串轉換為ASCII編碼的字節數組; 將ASCII更改為UTF8,您應該發送UTF-8:

void SendString(String message)
{
    byte[] buffer = Encoding.UTF8.GetBytes(message);
    AsyncCallback ac = new AsyncCallback(SendStreamMsg);
    tcpClient.GetStream().BeginWrite(buffer, 0, buffer.Length, ac, null);
}

你似乎在這個方法定義之上有很多不必要的編碼工作,但沒有更多的背景我不能保證上面的編碼工作是不必要的......

暫無
暫無

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

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