【问题标题】:Send unicode String from C# to Java将 unicode 字符串从 C# 发送到 Java
【发布时间】:2011-10-25 01:47:43
【问题描述】:

在 C# 方面,我有这个代码来发送 unicode 字符串

    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 字符串。怎么解决?

【问题讨论】:

  • “收不到”是什么意思?究竟会发生什么?
  • 为什么要将 utf-16 字符串转换为 utf-8 字节数组,然后再转换回 utf-16 字符串?

标签: c# java sockets unicode-string


【解决方案1】:

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

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

【讨论】:

  • 哦,很抱歉,我忘记了这一行。我修好了它,它工作。谢谢
  • 先生,我不知道如何使用stackoverflow。我只是看到帮助。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-22
  • 1970-01-01
相关资源
最近更新 更多