dtvgo28624 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.

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

Receiving... >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());
    out.write(os.getBytes("UTF-8"));
    

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 docker环境配置
  • ¥20 绿盟安全扫描--检测到目标站点存在javascript框架库漏洞
  • ¥30 Android STD快速启动
  • ¥15 如何使用simulink建立一个永磁同步直线电机模型?
  • ¥30 天体光谱图的的绘制并得到星表
  • ¥15 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现