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?

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

报告相同问题?

悬赏问题

  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件