Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

secret byte

Tell me please why? How correctly send UTF messages?

like image 800
Leo Avatar asked Feb 02 '12 20:02

Leo


People also ask

How many bytes is writeUTF?

writeUTF. Writes a string to the underlying output stream using modified UTF-8 encoding in a machine-independent manner. First, two bytes are written to the output stream as if by the writeShort method giving the number of bytes to follow.

What is the use of writeUTF method?

This method takes an ActiveX string and writes it into the message data buffer at the current position in UTF format. The data written consists of a 2-byte length followed by the character data.


1 Answers

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);
like image 179
Adam Zalcman Avatar answered Oct 20 '22 10:10

Adam Zalcman