简体   繁体   中英

android socket DataOutputStream.writeUTF

I write socket client:

clientSocket = new Socket("192.168.1.102", 15780);
outToServer = new DataOutputStream(clientSocket.getOutputStream());

All works. But I wont to send to server UTF -8 format messages and do so:

outToServer.writeBytes("msg#");//server tag
outToServer.writeUTF("hello");
//outToServer.writeUTF(str); //or another string
outToServer.writeBytes("\n");
outToServer.flush();

Messages become such:

秘密字节

Tell me please why? How correctly send UTF messages?

writeUTF() documentation says:

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.

You can encode the string as utf-8 yourself and then send the resulting byte array to the server using write() :

byte[] buf = "hello".getBytes("UTF-8");
outToServer.write(buf, 0, buf.length);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM