Search code examples
phppythonapachecometlong-polling

How to integrate a scalable long-polling server with PHP?


I've been "recruited" so to speak to help work on a web project that is currently written in PHP with an Apache server. We would like to integrate a real-time (or at least something very close to it) chat feature. Scalability is a definite concern, and this type of work is definitely not my typical.

Everything I've read about creating such a chat feature requires the use of "long-polling" so the servers don't get rapidly overloaded and, well, crash. PHP and Apache are not conducive to implementing such a feature, so I've explored some alternatives, like Twisted Python for example.

The website has roughly ~7,000 lines of PHP (i.e., it'd pretty difficult to just straight switch languages for the entire thing), so my question is how can I manage this situation as far as trying to integrate python and setting up a separate server? Or, is this a very bad way to do this? Are there other alternatives that would be better suited? (Sadly many of the PHP Comet, or even AJAX, solutions I've found don't scale in the slightest. Note, the Apache server is not necessarily required; however, any server used must work with PHP and Python etc, short of having separate servers.)

Thanks for the help!


Solution

  • I would use Tornado on the server to write the chat application. Client server communication can then be over websockets. If you use SockJS on the client side you can also support older browsers via long polling. There are plenty of example chat clients written using Tornado. It's very simple to get started and it is wonderfully scalable. A chat server like this can be serving thousands of clients without showing any appreciable CPU activity.

    This is an example, possibly a bit over engineered https://github.com/diggidanne/websocket-chat/blob/master/server.py