I have a problem when sending and receiving a string via socket. My application includes ac# client and java server. C# will send a string:
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);
}
}
and Java receive :
int lenght=readIntFromDotNet(reader);
if(lenght>0)
{
byte[] buffer = new byte[lenght];
reader.read(buffer, 0, lenght);
return new String(buffer);
}
Problem: the received string is wrong .
example: C# send "Variable" and java receive "V ariable"
What's wrong in my code?
Solved : i have used "UTF-16LE"
return new String(buffer,"UTF-16LE");
May be this would do the trick for you
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);
}
on the Java side
Charset utf8 = Charset.forName("UTF-8");
bufferReader = new BufferedReader(new InputStreamReader(sockServer.getInputStream(),utf8));
String message = br.readLine();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.