Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way for keeping the client browser informed about events (like a new chat message)?

The common way, I think, is making a periodic "ping" to the server, but I don't like how it looks too much like

"Is there anything new? - No"
"Is there anything new? - No"
"Is there anything new? - No"
"Is there anything new? - No"
"Is there anyt..."

I've seen another approach where client ask for news and server "retains" the request (with a sleep loop, for example) until there is anything new. That's cool, but I'd really like to hear about another options.

like image 594
Erik Escobedo Avatar asked Dec 17 '22 23:12

Erik Escobedo


2 Answers

Unfortunately there isn't really any cross browser mechanism for pushing data from the server to the browser. For example, back in 1995 Netscape released a server push technology that uses a special content type -- multipart/x-mixed-replace but from what I understand IE doesn't support it. WebSockets are a new one but support is just coming out now.

So you're forced to use the tools at hand, which means the client needs to ask the server if there's any new data -- polling. Polling comes in 2 varieties: polling on an interval, and long polling. When you poll on an interval you simply make a request to the server every n seconds asking for data. This is fairly chatty (pardon the pun) if there is no new data to return. This is what people think of when you say "polling."

The other option, long polling, is similar in that the client makes a request to the server to see if there's new data. But in this case the server doesn't send a response until it has something to say. In this case the client is left hanging for a response for an undetermined amount of time. When the client eventually gets its response it parses the response and immediately makes another request which will stay hanging until there's data.

Both of these polling approaches consume a lot of HTTP overhead, but if you want to use XHRs this is about the only way to do it.

A word of warning about long polling: When working with long polling it's important to ensure that all of your XHRs are running asynchronously otherwise you'll see the browser's UI thread lock up.


If you're not interested in using AJAX then you can always use the tried and testing IFRAME-that-never-finishes-loading. In this case you have an IFRAME with the chat log and another IFRAME that contains your message area. In this case the server simply never closes the connection for the IFRAME that contains the chat log. Instead, it just keeps pushing chat messages into the body.

like image 100
Bryan Kyle Avatar answered Jan 25 '23 23:01

Bryan Kyle


WebSockets can be helpful if you're okay if some browsers aren't able to use it.

If you want to it in JavaScript, there is no alternative to polling in intervals.

like image 45
jigfox Avatar answered Jan 26 '23 00:01

jigfox