0

I have a java server communicating with a PHP script called from apache. I am aiming to send a JSON from the java server to the php client when requested, however there is some stuff getting prefixed when its received on the client.

JAVA

in = new BufferedReader(new InputStreamReader (socket.getInputStream()));                  
out= new DataOutputStream(socket.getOutputStream());

//The server receives a JSON from the PHP script and replies. It recives and converts to a Gson JSON no problem.

String reply = "{\"status\":\"reg\",\"token\":\""+client.getToken()+"\"}\r\n";
//reply = "HELLO\r";
out.writeUTF(reply);

PHP

$rec = socket_read($socket, 2048,PHP_NORMAL_READ);
echo "Receiving... ";
echo $rec;

The issue is that the message received is pre-fixed with some crap.

Output From PHP

Receiving... 1{"status":"reg","token":"QOPIPCNDI4K97QP0NAQF"}

If I send "HELLO\r"

Receiving... >HELLO

Florent Bayle
  • 11,520
  • 4
  • 34
  • 47
Andrew
  • 1,764
  • 3
  • 24
  • 38

1 Answers1

2

You shouldn't use DataOutputStream.writeUTF() unless you are using DataOutputStream.readUTF() to read the message.

Here is a snippet of the javadoc of 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. This value is the number of bytes actually written out, not the length of the string. Following the length, each character of the string is output, in sequence, using the modified UTF-8 encoding for the character. If no exception is thrown, the counter written is incremented by the total number of bytes written to the output stream. This will be at least two plus the length of str, and at most two plus thrice the length of str.

The bolded part above may tell you why you are getting weird characters at the beginning of your message.

Here is a workaround I believe will work in your case

BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
out.write(os.getBytes("UTF-8"));

Reference: Why does DataOutputStream.writeUTF() add additional 2 bytes at the beginning?

Community
  • 1
  • 1
dlock
  • 9,447
  • 9
  • 47
  • 67