简单的PHP长轮询聊天脚本,太简单了吗? [英] Simple PHP long polling chat script, too simple?

查看:183
本文介绍了简单的PHP长轮询聊天脚本,太简单了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个简单的聊天应用程序,每个房间可能有10至20个用户.

Im working on a simple chat app, probably 10 to 20 users per room.

查询数据库中新消息的脚本对于它将要收到的所有请求来说似乎太简单了.

The Script that queries the database for new messages looks too simple for all the request it'll be getting.

下面是循环生成新消息的代码块,脚本的其余部分只是获取变量,查询的构造和json响应对象:

Below is the block of code that loops for new messages, the rest of the script is just getting the variables, construction of the query and the json response object:

$sleepTime = 1; //Seconds
$data = "";
$timeout = 0;

//Query database for data
while(!$data and $timeout < 10){
    $data = getQuery($sql);
    if(!$data){
        //No new messages on the chat
        flush();
        //Wait for new Messages
        sleep($sleepTime);          
        $timeout += 1;
    }else{
        break;
    }
}

上面的块将在10秒钟内每秒查询一次数据库中的新消息,如果在10秒钟后没有新消息,它将通知浏览器.浏览器等待5秒钟,然后发送另一个请求 以获得新消息.

The block above will query the database for new messages every second for 10 seconds, if after the 10 seconds there are no new messages it will notify the browser. The browser waits 5 seconds and then sends another request to get new messages.

但是,如果脚本发现新消息,则浏览器将在从服务器获得新消息的响应后立即请求更多新消息.

However If the script finds new messages, the browser will request more new messages instantly as soon as it gets the response with the new messages from the server.

此过程一直在进行...

This process goes on and on...

那么我该如何进一步优化此过程? 这是否尽善尽美? 在我的本地服务器上运行良好,但是我担心只有少数几个用户可能会因为所有请求和循环而使活动服务器(共享主机)超载.

So how can i optimize this process any further? Is this as good as it gets? Is working fine on my local server, but im afraid that just a few users could overload a live server(shared host) with all the requests and the loopings.

这是实时演示,您可以使用萤火虫 http://pixbush.com/chat/chat.php进行检查

Here is live DEMO you can check with firebug http://pixbush.com/chat/chat.php

推荐答案

从您的描述中看来,您有5秒钟的沉默间隔,这抵消了长轮询的好处.当服务器从呼叫返回(多头或空头)时,让浏览器立即启动另一个请求.作为备份,每次服务器调用时,都应让浏览器启动的超时时间稍长于服务器端的超时时间,但在返回请求时将其取消.如果服务器请求失败并且浏览器超时完成,请启动新请求.

From your description, it sounds like you have a 5 second gap of silence which defeats the benefit of long-polling. Have the browser start another request immediately when a call returns (long or short) from the server. As a back up, with each server call, have the browser start a timeout slightly longer than the server-side timeout, but cancel it when a request is returned. If the server request ever fails and the browser timeout completes, start a new request.

这篇关于简单的PHP长轮询聊天脚本,太简单了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆