在我的项目中,有私有(private)聊天和消息通知等功能。 消息通知让我们知道是否有新的未读消息。
为了实现这一目标,我想到的想法是
Like in a
client
-server
model , the server should listen for the new requests. Like that , I thought there should be some mechanism to listen to the server for getting information about new messages . Since I know ajax , I usedajax
request with an interval of 2seconds.
But I thought afterward that, StackOverflow should use the same trick if it was the only idea to do so since they update notifications / vote information asynchronously .
在 Chrome 中检查他们的 ajax 请求,它完全是空白。
我需要知道如何在不使用频繁的ajax请求(这会增加服务器的负载)的情况下实现它。
一个具有最有效技术的简单示例对于学习非常有用。
最佳答案
这被称为 Comet ,有几种方法可以实现:
- 轮询(您正在做什么 - 定期检查是否有消息)
- 长轮询(发出在收到消息之前不会得到响应的请求)
- 流式传输(打开脚本连接,以增量方式发送可执行 JavaScript 更新)
- Websockets(最好的选择,如果支持的话 - 所有其余的都是针对 Websockets 最终要解决的问题进行的黑客攻击)
实现它们很棘手,这里有许多库可供选择,可以为您正确实现它们(例如 Socket.IO)。
编辑:
A simple example with the most efficient technique would be very useful for learning.
正如我所说,您不想自己实现这些,因为它们很棘手且充满危险;大多数好的Comet库都会考虑浏览器的特性并选择最佳的协议(protocol),这样对于程序员来说是透明的,使得使用这种模型进行开发变得非常容易。例如,查看 Socket.IO tutorials .
另请注意,您需要一台能够处理 Comet 的服务器:例如Socket.IO 与 Node.JS 配合使用。例如,它们不能与默认的 Apache 一起使用。
关于jquery - 客户端如何在不频繁ajax请求的情况下从服务器获取更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37096408/