Server-push whenever a function is called: Ajax or

2019-09-03 11:52发布

问题:

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.

回答1:

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.

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.


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.

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.

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.