Using BOSH to create a real-time, Javascript chat client

For iWink I have written a short article about the development of a Javascript only chat-client.

Deze techniek werkt als volgt: zodra een webpagina is geladen, zorgt een stukje code op deze pagina ervoor dat in de achtergrond nog een extra verbinding gemaakt wordt met de webserver. De webserver laat deze verbinding open staan en geeft geen antwoord, totdat er een chatbericht voor deze bezoeker ontvangen wordt. De webserver stuurt dan het chatbericht over de al gereedstaande verbinding. Hiermee kan een chatbericht binnen enkele honderden milliseconden afgeleverd worden.

You can read the full article here: A Faster Chat (Dutch).

The chat module is written entirely in Javascript and is based on the Prototype framework. For effects and animations, Script.aculo.us is used. Some notes:

  • It is really hard to detect if a connection is still in use with PHP. Of course there is connection_aborted(), but this only works if a TCP RST packet has been received. This only happens when a user actually clickes the stop button in his or her browser, and with AJAX requests only when transport.abort() is invoked. The only solution is time-outs, but that’s not very responsive.
  • The chat uses long-living Apache processes. That’s okay when there are, say, less than fifty clients using the chat function at the same time, but when you would have more clients the server would quickly run out of memory. Fortunately, memory is cheap. If you need more clients, you could use an HTTP server implementation in Erlang, as Facebook has done.
  • It’s hard to create an event based system in PHP that does not tax the server too much. A MySQL table is continuously queried. Fortunately the MySQL Query Cache keeps the load acceptable. After each query, a short usleep() command is issued.
  • Keeping connections open really saves on traffic. Open connections do not use any bytes. An AJAX polling method would use several hundreds of bytes per request on headers alone, this would quickly add up. Open connections use only bytes when there is something to send.
  • The chat client requires quite an amount of Javascript. In order to speed up delivery to the browser, we use the JSMin++ Javascript minifier developed by Crisp.

About this entry