[英]Send unicode String from C# to Java
On C# side, I have this code to send unicode String 在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
}
and this is Java side 这是Java方面
Charset utf8 = Charset.forName("UTF-8");
bufferReader = new BufferedReader(new InputStreamReader(
sockServer.getInputStream(),utf8));
String message = br.readLine();
The problem is I cannot receive unicode string on Java side. 问题是我无法在Java端接收unicode字符串。 How can resolve it?
怎么解决呢?
Your question is a bit ambiguous; 您的问题有点模棱两可; You say you cannot receive unicode string on the Java side - Are you getting an error, or are you getting an ASCII string?
你说你不能在Java端接收unicode字符串 - 你是收到错误,还是得到一个ASCII字符串? I'm assuming you are getting an ASCII string, because that is what your SendString() method is sending, but maybe there are additional issues.
我假设您正在获取ASCII字符串,因为这是您的SendString()方法发送的,但可能还有其他问题。
Your SendString() method starts out by converting the passed in string to an array of bytes in ASCII encoding; 您的SendString()方法首先将传入的字符串转换为ASCII编码的字节数组; Change ASCII to UTF8 and you should be sending UTF-8:
将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);
}
You also seem to have a lot of unnecessary encoding work above this method definition, but without more background I can't guarantee that the encoding work above it is unnecessary... 你似乎在这个方法定义之上有很多不必要的编码工作,但没有更多的背景我不能保证上面的编码工作是不必要的......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.