通过套接字发送和接收字符串时遇到问题。我的应用程序包括一个c#客户端和java服务器。 C#将发送一个字符串:
c#code:
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#发送“变量”,java接收“V a r i a b l e”
我的代码出了什么问题?
解决了:我使用过“UTF-16LE”
return new String(buffer,"UTF-16LE");
答案 0 :(得分:0)
可能会为你做这个伎俩
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();