douji2283 2013-02-18 17:27
浏览 69

Long Polling或Comet如何使用PHP?

I am making a notification system for my website. I want the logged in users to immediately noticed when a notification has made. As many people say, there're only a few ways of doing so.

One is writing some javascript code to ask the server "Are there any new notifications ?" at a given time interval. It's called "Polling" (I should be right).

Another is "Long Polling" or "Comet". As wikipedia says, long polling is similar to polling. Without asking everytime for new notifications, when new notifications are available, server sends them directly to the client.

So how can i use Long Polling with PHP ? (Don't need full source code, but a way of doing so) What's its architecture/design really ?

  • 写回答

4条回答 默认 最新

  • drtohng5613 2013-02-18 17:31
    关注

    The basic idea of long-polling is that you send a request which is then NOT responded or terminated by the server until some desired condition. I.e. server-side doesn't "finish" serving the request by sending the response. You can achieve this by keeping the execution in a loop on server-side.

    Imagine that in each loop you do a database query or whatever is necessary for you to find out if the condition you need is now true. Only when it IS you break the loop and send the response to the client. When the client receives the response, it immediately re-sends the "long-polling" request so it wouldn't miss a next "notification".

    A simplified example of the server-side PHP code for this could be:

    // Set the loop to run 28 times, sleeping 2 seconds between each loop.
    for($i = 1; $i < 29; $i++) {
    
        // find out if the condition is satisfied.
        // If YES, break the loop and send response     
    
        sleep(2);
    }
    // If nothing happened (the condition didn't satisfy) during the 28 loops,
    // respond with a special response indicating no results. This helps avoiding
    // problems of 'max_execution_time' reached. Still, the client should re-send the
    // long-polling request even in this case.
    
    评论

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大