开发者

Ways to send a message from the server to the web browser at any time?

开发者 https://www.devze.com 2023-01-31 23:30 出处:网络
I\'m in a situation where I want to be able to notify a visitor to my website of an event occurring at the server.

I'm in a situation where I want to be able to notify a visitor to my website of an event occurring at the server.

Think:

  • Website visitor is waiting for an export or report that takes a long time and is running in the background on the server, need to notify visitor when export is done.

or

  • Website visitor is waiting f开发者_运维问答or a chat message from a sales rep, need to notify visitor when a message is sent to them.

I can think of a few ways to do this:

  • Keep an HTTP connection to the server open forever
  • Continually polling the HTTP server every second to check if there are new messages
  • Write a Java applet that holds a connection open to a Java server process

None of these seem particularly graceful solutions... is there a better way to do this?


HTTP is a client-server protocol so it doesn't allow for server initiated communications.

There are a number of workarounds for this scenario and you have come up with most of them.

  1. The most common and low tech technique is just polling. You can see this on most on-line travel agencies when you search for a flight.
  2. Keeping a connection open until it times out and then opening another waiting for the server to send something is called Comet and it is implemented in many ways, sometimes even with a Java Applet.
  3. The most recent standard way to do this is with WebSockets, which give you a full-duplex (2 way) channel wherein you can do anything you want. It is a brand new protocol which manhandles HTTP just to open the connection. The only drawback is that it's rather new so check browser compatibility. Checkout the demos.


As far as I'm concerned, the best way to approach this is to have the client poll the server. I don't know of any way to force information to a client's browser.

I would think polling from some sort of JavaScript/AJAX would be ideal.


As far as I know you cannot open sockets (Connections through network interfaces) from java applets. That is a part of the secutiry policy.

0

精彩评论

暂无评论...
验证码 换一张
取 消