2014-03-10 11:02
浏览 28

Java> PHP Socket - 消息开头的垃圾

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.


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()+"\"}
//reply = "HELLO";


$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"

Receiving... >HELLO

图片转代码服务由CSDN问答提供 功能建议

我有一个java服务器与从apache调用的PHP脚本进行通信。 我的目标是在请求时从Java服务器向php客户端发送一个JSON,但是当它在客户端收到时会有一些东西被加上前缀。

JAVA in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new DataOutputStream(socket.getOutputStream()); //服务器从PHP脚本接收JSON并回复。 它重现并转换为Gson JSON没问题。 String reply =“{\”status \“:\”reg \“,\”token \“:\”“+ client.getToken()+”\“ } “; // reply =”HELLO “; out.writeUTF(回复);

PHP \ n

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



接收... 1 {“状态”:“reg”,“令牌”:“QOPIPCNDI4K97QP0NAQF “}

如果我发送”HELLO “

接收...> HELLO

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douxin2011 2014-03-10 11:11

    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());

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

    打赏 评论