Ever wanted to add a small chat to your own website? If you look around you'll find plenty of ways to do so,
some use Flash, others PHP and a database and there are even some Java applets out there (they still exist!).
However when searching for a really simple chat I could integrate into the website of the 6th gamesday
I found nothing that satisfied me: I didn't need logins or a user management nor multiple chat rooms, just a
basic chat thats simple to handle and don't need maintenance.
Because of this I created my own chat with a few lines of PHP and JavaScript. The Simple Chat project
is the refined and further simplified version of this chat:
- New messages are appended to a text file on the server. It contains only the newest 10 messages, older ones
are thrown away. Optionally the new message is also appended to a full chat log.
- Every client requests this text file every two seconds and displays all new messages inside it. This may sound
like a heavy load but since it's only an ordinary text file the webserver can delivery it very fast and HTTP
caching helps, too.
That's pretty much it. 20 lines of PHP and about 40 lines of JavaScrip (with help from jQuery I admit). Not even
a database and therefore nothing to keep an eye on. Just three simple files (if you include jQuery) and you can
copy them around as you like. Take a look at the source code, it's really not much. If you need a small chat
for your website feel free to use this code and extend or modify it as needed.
Performance wise I was a bit surprised. I wrote a small (and lousy) Ruby script to simulate multiple clients but even
with 150 simulated clients the load on the webserver and I/O was still negligible (the test script eat almost all CPU
time). The test script can't simulate more than 150 clients due to threading overhead (at least that's what I suspect)
and one could write another more scalable test script but with 150 clients the chat can withstand much much more
than it will ever get.
I've written an in depth explanation of the architecture and code but that's something for tomorrow. For now the
idea and the code should speak for them selfs. If you have questions feel free to write a comment. :)