Java > PHP Socket - trash at start of message -
i have java server communicating php script called apache. aiming send json java server php client when requested, there stuff getting prefixed when received on client.
java
in = new bufferedreader(new inputstreamreader (socket.getinputstream())); out= new dataoutputstream(socket.getoutputstream()); //the server receives json php script , replies. recives , converts 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 message received pre-fixed crap.
output php
receiving... 1{"status":"reg","token":"qopipcndi4k97qp0naqf"}
if send "hello\r"
receiving... >hello
you shouldn't use dataoutputstream.writeutf()
unless using dataoutputstream.readutf()
read message.
here snippet of javadoc of writeutf()
:
writes string underlying output stream using modified utf-8 encoding in machine-independent manner.
first, 2 bytes written output stream if writeshort method giving number of bytes follow. value number of bytes written out, not length of string. following length, each character of string output, in sequence, using modified utf-8 encoding character. if no exception thrown, counter written incremented total number of bytes written output stream. @ least 2 plus length of str, , @ 2 plus thrice length of str.
the bolded part above may tell why getting weird characters @ beginning of message.
here workaround believe work in case
bufferedoutputstream out = new bufferedoutputstream(socket.getoutputstream()); out.write(os.getbytes("utf-8"));
reference: why dataoutputstream.writeutf() add additional 2 bytes @ beginning?
Comments
Post a Comment