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 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?