[英]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.