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 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 spring后端vue前端
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题