将 unicode 字符串从 C# 发送到 Java
在 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 字符串。怎样才能解决呢?
On C# side, I have this code to send 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
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. How can resolve it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的问题有点含糊;你说你无法在 Java 端接收 unicode 字符串 - 你是否收到错误,或者你收到 ASCII 字符串?我假设您收到的是 ASCII 字符串,因为这就是您的 SendString() 方法发送的内容,但可能还有其他问题。
SendString() 方法首先将传入的字符串转换为 ASCII 编码的字节数组;将 ASCII 更改为 UTF8,您应该发送 UTF-8:
您似乎还在此方法定义之上进行了很多不必要的编码工作,但没有更多背景,我不能保证上面的编码工作是不必要的......
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? I'm assuming you are getting an ASCII string, because that is what your SendString() method is sending, but maybe there are additional issues.
Your SendString() method starts out by converting the passed in string to an array of bytes in ASCII encoding; Change ASCII to UTF8 and you should be sending UTF-8:
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...