我写套接字客户端:
clientSocket = new Socket("192.168.1.102",15780); outToServer = new DataOutputStream(clientSocket.getOutputStream());
一切都有效.但我不会发送到服务器UTF-8格式的消息,并这样做:
outToServer.writeBytes("msg#");//server tag outToServer.writeUTF("hello"); //outToServer.writeUTF(str); //or another string outToServer.writeBytes("\n"); outToServer.flush();
消息变成这样:
请告诉我为什么?如何正确发送UTF消息?
解决方法
writeUTF()
documentation说:
First,two bytes are written to the output stream as if by the writeShort method giving the number of bytes to follow. This value is the number of bytes actually written out,not the length of the string.
您可以自己将字符串编码为utf-8,然后使用write()
将生成的字节数组发送到服务器:
byte[] buf = "hello".getBytes("UTF-8"); outToServer.write(buf,buf.length);