简体   繁体   English

如何使用新消息更新聊天窗口

[英]how to update chat window with new messages

setInterval(function{

 //send ajax request and update chat window


}, 1000)

is there any better way to update the chat with new messages?有没有更好的方法用新消息更新聊天? is this the right way to update the chat using setInterval?这是使用 setInterval 更新聊天的正确方法吗?

There are two major options (or more said popular ways)有两种主要选择(或更多的流行方式)

Pulling

First is pulling, this is what you are doing.首先是拉动,这就是你正在做的事情。 Every x (milli)seconds you check if the server config has changed.每 x (milli) 秒检查服务器配置是否已更改。

This is the html4 way (excluding flash etc, so html/js only).这是 html4 方式(不包括 flash 等,因此仅限 html/js)。 For php not the best way because you make for a sinle user a lot of connections per minute (in your example code at least 60 connections per second).对于 php 不是最好的方法,因为您每分钟为单个用户创建大量连接(在您的示例代码中,每秒至少有 60 个连接)。

It is also recommended to wait before the response and then wait.也建议在响应之前等待,然后等待。 If for example you request every 1 second for an update, but your response takes 2 seconds, you are hammering your server.例如,如果您每 1 秒请求一次更新,但您的响应需要 2 秒,那么您正在锤击您的服务器。 See tymeJV answer for more info有关更多信息,请参阅tymeJV 答案

Pushing

Next is pushing.接下来是推。 This is more the HTML5 way.这更像是 HTML5 的方式。 This is implemented by websockets.这是由 websockets 实现的。 What is happining is the client is "listing" to a connection and waiting to be updated.令人高兴的是客户端正在“列出”连接并等待更新。 When it is updated it will triger an event.当它被更新时,它会触发一个事件。

This is not great to implement in PHP because well you need a constanct connection, and your server will be overrun in no time because PHP can't push connections to the background (like Java can, if I am correct).这不太适合在 PHP 中实现,因为您需要一个持续的连接,并且您的服务器很快就会溢出,因为 PHP 无法将连接推送到后台(就像 Java 可以,如果我是对的)。

I made personally a small chat app and used pusher .我个人制作了一个小型聊天应用程序并使用了pusher It works perfectly.它完美地工作。 I only used the free version so don't know how expensive it is.我只用过免费版,不知道贵不贵。

Pretty much yes, one minor tweak, rather than encapsulate an AJAX call inside an interval (this could result in pooling of unreturned requests if something goes bad on the server), you should throw a setTimeout into the AJAX callback to create a recursive call.几乎是的,一个小调整,而不是在一个时间间隔内封装 AJAX 调用(如果服务器出现问题,这可能导致未返回请求的池化),您应该将setTimeout放入 AJAX 回调中以创建递归调用。 Consider:考虑:

function callAjax() {
    $.ajax(options).done(function() {
        //do your response
        setTimeout(callAjax, 2000);
    });
}

callAjax();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM