csdn产品小助手 2014-05-01 13:51 采纳率: 0%
浏览 29

PHP流数据到AJAX调用

Following this information:

I was hoping to achieve the following:

  • AJAX -> (POST)PHP(socket) -> (socket)Python

By doing:

$.ajax({
    type: "POST",
    url: "post.php",
    async: true,
    cache: false,
    data: { data : 'ping 127.0.0.1' },
    success: function(msg) {
        console.log(msg);
    }
});

With PHP looking like:

//header("Connection: close");
//header("Content-Type: application/octet-stream");
socket_write($socket, 'ping 127.0.0.1', strlen('ping 127.0.0.1'));
ignore_user_abort();
//ob_implicit_flush(true);
//ob_end_flush();
while ($out = socket_read($socket, 8192)) {
    echo $out;
    ob_flush();
}
//ob_start();

And Python simply doing:

sock.recv(8192)
for i in range(0, 4):
    sock.send(bytes(json.dumps('Ping successfull..'), 'UTF-8'))
    sleep(0.5)

I thought I'd be able to buffer out the data in "real-time" instead of ending up with the data bunched up like this:

"Ping successfull..""Ping successfull..""Ping successfull..""Ping successfull.."

Where did i go wrong in my thinking? This should be quite straight forward? I've done it so many times but yet this time I can't figure out what i'm doing wrong :/

I've also verified that it is indeed the AJAX/PHP bridge not working, PHP recieves the data as it arrives, verified with strftime("%H:%M:%S") and i get the expected difference in between each recieves.

  • 写回答

1条回答 默认 最新

  • weixin_33699914 2014-05-01 14:17
    关注

    AJAX uses HTTP, so the callback for success/failure is only called when the request completes and there are no options for getting the data while it's being received. You should check out web sockets, which will allow you to handle streaming data from the server.


    Edit: You could also look at multipart/x-mixed-replace and EventSource

    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料