1

在 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 字符串。如何解决?

4

1 回答 1

3

你的问题有点模棱两可;你说你不能在 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);
}

您似乎在此方法定义之上还有很多不必要的编码工作,但没有更多背景我不能保证它上面的编码工作是不必要的......

于 2011-10-25T02:02:18.610 回答