@dmjpro
You
really think right. Because I programmed a google-like chat for an intranet of a big company from scratch.
There were 3 problems because of third-party-software: no EJB container and no session movement or application server control.
On the client side (browser), there runs an Ajax read-request every second that sends the actual lastDisplayedChatLineNumber over. It will then get all lines that are newer (or none if there is no new entry) from the server, display them and increase lastDisplayedChatLineNumber accordingly.
On the serverside, you can make a class Chat that has a
static hashtable that holds all the chat data and a static variable lastChatLineNumber.
When a read-request from the client comes in, you compare lastDisplayedChatLineNumber with lastChatLineNumber and send the missing lines over. If a write-request comes in (if a user sends a new line from any client), you just increase lastChatLineNumber and store the new line in your hashtable.
It works without any further communication mechanism, because the static class data is shared among all threads. That's also the quickest communication.
So if you only have one application server (and one JVM instance), you don't need to worry further.
But it doesn't work if the sessions of two users in the same chat-room are on different application-servers. In this case, the simplest solution is to make sure that this can't happen. Either move the session from one application-server to the second, or make sure that all logins of different users to the
same chat-room are only going to the
same server.
If you can't control that (like in my case because of stupid third-party loadbalancer), then you must use Corba, RMI or something else (see post before) to communicate between the 2 threads. Because we had no EJB container and RMI crashed because of closed ports, I used the database-approach: I created a small table that holds the lastChatLineNumber column. All application-servers accessed the same (clustered) database. At every read-request, I read this number from DB and compared it with my own static lastChatLineNumber variable value. Then only in case it was different, I read the missing lines from a second, big table that holds all the chat-lines. At every write-request, I increased this number in the small database table and stored the corresponding line in the big table.
This works well, but isn't efficient for big traffic. If you still can't use corba or EJB, then at least you can use two tricks to minimize traffic:
Network-traffic: If a user doesn't type anything for at least 15 seconds, then his Ajax-requests will only inquire every minute instead of every second.
Database-traffic: Instead of doing it at every inquiry, an independent thread can synchronize the static variable lastChatLineNumber with the database every 3 seconds.