[英]C# send a string and Java received wrong string via Socket
通过套接字发送和接收字符串时出现问题。 我的应用程序包括ac#客户端和Java服务器。 C#将发送一个字符串:
C#代码:
this.WriteByteArray(Encoding.Unicode.GetBytes(variable))
this.WriteByteArray(Encoding.Unicode.GetBytes(value.ToString()));
reader.ReadBoolean();
private void WriteByteArray(byte[] buffer)
{
writer.Write(buffer.Length);
if (buffer.Length > 0)
{
writer.Write(buffer);
}
}
和Java接收:
int lenght=readIntFromDotNet(reader);
if(lenght>0)
{
byte[] buffer = new byte[lenght];
reader.read(buffer, 0, lenght);
return new String(buffer);
}
问题:收到的字符串错误。
示例:C#发送“ Variable”,而Java接收“ V ariable”
我的代码有什么问题?
解决 :我用过“ UTF-16LE”
return new String(buffer,"UTF-16LE");
也许这会为您解决问题
this.WriteByteArray(variable)
reader.ReadBoolean();
void WriteByteArray(String message)
{
byte[] buffer = Encoding.UTF8.GetBytes(message);
AsyncCallback ac = new AsyncCallback(SendStreamMsg);
tcpClient.GetStream().BeginWrite(buffer, 0, buffer.Length, ac, null);
}
在Java方面
Charset utf8 = Charset.forName("UTF-8");
bufferReader = new BufferedReader(new InputStreamReader(sockServer.getInputStream(),utf8));
String message = br.readLine();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.