调用函数时服务器推送:Ajax 或 WebSockets [英] Server-push whenever a function is called: Ajax or WebSockets

查看:22
本文介绍了调用函数时服务器推送:Ajax 或 WebSockets的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在 Tornado (python) 中开发状态仪表板.每当调用外部函数时,我都需要动态更新网页(通过重新渲染模板).我很好奇实现这一目标的最有效方法是什么?他们有没有类似的教程.

I am currently working on a status-dashboard in Tornado (python). I need to have the web page dynamically update (by re-rendering a template) whenever an outside function is called. I was curious what is the most efficient way to accomplish this? and are their any tutorials out there for something similar.

推荐答案

如果您想要实际的服务器推送,那么您将需要 webSocket 或服务器发送的事件.由于服务器发送的事件是非常新的(并且在很多浏览器中都不支持),因此实际服务器推送的主要选项是 webSocket 连接.

If you want actual server push, then you will need either webSocket or server-sent events. Since server-sent events is very new (and not supported in very many browsers), your main option for actual server push is a webSocket connection.

在 webSocket 架构中,客户端连接到服务器,然后保持连接.这允许服务器随时通过该连接向客户端发送数据.

In the webSocket architecture, the client connects to the server and then stays connected. This allows the server to send data to the client over that connection at any time.

服务器发送的事件是一种类似的架构,但其使用方式有不同的实现细节.

Server-sent events are a similar architecture, but with different implementation details for how it is used.

没有办法使用 Ajax 进行实际的服务器推送.Ajax 有时用于通过使用通常称为长轮询的方式来模拟服务器发送的事件.在这种情况下,客户端进行 Ajax 调用,服务器只是在 Ajax 请求上挂起一段时间,而不是立即返回响应.如果在此期间服务器端事件到达,则服务器可以获取正在等待响应的连接并发送响应.客户端将获得响应,对其进行处理,然后进行另一个 Ajax 调用.在长轮询中,如果一段时间后没有发生服务器端动作,则 Ajax 调用超时,客户端必须发起新连接.

There is no way to use Ajax for actual server-push. Ajax is sometimes used to simulate server-sent events by using what is commonly called long polling. In this scenario, a client makes an Ajax call and the server just hangs onto the Ajax request for awhile, not immediately returning a response. If a server-side event arrives during this time, then the server can take the connection that is awaiting a response and send a response. The client will get the response, process it and it then makes another Ajax call. In long polling, if no server-side action happens after awhile, the Ajax call times out and the client has to initiate a new connection.

长轮询的整个连接序列通常比 webSocket 连接效率低.因此,如果您要解决的主要问题是服务器推送,那么 webSocket 连接可能是获得广泛支持的最有效方法.

The whole connection sequence with long polling is generally less efficient than a webSocket connection. So, if the primary problem you're trying to solve is server-push, then a webSocket connection will likely be the most efficient way to do it that is widely supported.

以下是一些类似的问题和答案,其中包含更多讨论:用于实时数据的 websocket 与 rest API?Ajax 与Socket.io.

Here are some similar questions and answers that contains some more discussion: websocket vs rest API for real time data? and Ajax vs Socket.io.

这篇关于调用函数时服务器推送:Ajax 或 WebSockets的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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