在 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 字符串。怎么解决?
最佳答案
你的问题有点模棱两可;你说你不能在 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);
}
你似乎在这个方法定义之上还有很多不必要的编码工作,但是没有更多的背景我不能保证上面的编码工作是不必要的......
关于c# - 将 unicode 字符串从 C# 发送到 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7883831/