If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

Design pattern of chat

Hi,

I've written a chat using ajax. In a nutshell, every few seconds, an ajax call is fired and data is getting updated. The ajax function is a setTimeout in itself, so the loop goes on.

What's bothering me is that, when a page is open on my computer, it will send requests forever. So if I reduce setTimeout time to have more live/instant experience, I'd be firing a lot of redundant requests because most of them aren't necessary. I'd like to know if there's a way to only send the request if there's an update on the server. So instead of sending ajax and wait for response, just "listen" for a response?

Maybe I'm trying to ask if there's a way to have a response on a page without "requesting by ajax"?
All alternative ways are welcome.

You can use a technique called "comet", which works with AJAX. In this technique the clients send requests to the server, and wait for an answer which will be send by the server only when there is some new information.

EventSource and WebSockets are two newer tech that can provide a much better chat product than ajax.

if you must use ajax, use long polling to keep the connection open until new data is ready to send.
with an optimized long-poll. i've gotten the bandwidth waste down to ~200KB/day, including packet headers.

You can run node.js and socket-io on a different port than Apache2.. such as 8080, and connect your web application to that port instead of the default port 80. That is, if you aren't using shared hosting. If your host only supports PHP, you are pretty much stuck doing it the inefficient way.. that is, continuous polling. You can work harder than you have to in order to implement some kind of long-polling program, but PHP and Apache2 are likely to break-down- despite the hours it will take to successfully implement it.

I have root access and I use nginx and PHP. So basically the idea is making long-requests via AJAX, depending on my nginx timeout. But I'd need long-polling server so that it doesn't tie all my web server workers.

I have root access and I use nginx and PHP. So basically the idea is making long-requests via AJAX, depending on my nginx timeout. But I'd need long-polling server so that it doesn't tie all my web server workers.

Server-Sent-Events (EventSource) is going to be WAY easier to impliment than sockets, and about as good for chat, since you can SEND from the client instantly.
it's basically a simplified HTTP protocol.

im sure google has their own custom java chat code like have for all their other stuff.
we're not talking about your grandma's java, it's a custom build for custom hardware, very slick stuff.