How Can a LAMP Guy Easily Implement WebSockets?
Question: I've always worked with Apache, MySQL, and PHP. I'd like to eventually branch
out to Python/Django or Ruby/Ruby on Rails, but that's another discussion. Two
great things about Apache, MySQL, and PHP are all three are ubiquitous and
it's very easy to launch a website. Just set up an Apache virtual host, import
the database into MySQL, and copy the PHP files onto the server. That's it.
This is all I've ever done and all I've ever known. Please keep this in mind.

These days, it's becoming increasingly important for websites to be able to
deliver data in real-time to the users. Users expect this too due to the live
nature of Facebook and Gmail. This effect can be faked with Ajax polling, but
that has a lot of overhead, as explained
[here](https://www.youtube.com/watch?v=cdDug2U29wk#t=6m). I'd like to use
WebSockets. Now remember that I've always been a LAMP guy. I've only ever
launched websites using the method I described earlier. So if I have, say, a
CakePHP site, how can I "add on" the feature of WebSockets? Do I need to
install some other server or something or can I get it to work smoothly with
Apache? Will it require Apache 2.4? Please explain the process to me keeping
in mind that I only know about LAMP. Thanks!


Answer: One key thing to keep in mind, is that a realtime websockets server needs to
be "long running", so that it can push stuff to clients. In the classic LAMP
setup, Apache spawns a PHP interpreter on each request. Between requests the
PHP interpreter is not running, and the only protocol state kept between
requests is sessions.

One nice property of the LAMP way, is that memory management is easy. You just
implicitly allocate whatever memory you need, and it is automatically
reclaimed when the request is done, and the PHP process exits. As soon as you
want the server to keep running, you need to consider memory management. In
some laguages, like C++, you manage allocation and deallocation explicitly. In
other languages, like Java or Javascript, you have garbage collection. In PHP
you throw everything away, and start with a fresh slate on each request.

I think you will have a hard time making long running servers with something
like Cake or any other classic PHP framework. Those frameworks works by
basically taking an HTTP request and turning it into an HTTP response.

My advice is that you should look into something like Node.JS and SocketIO. If
you know Javascript, or don't mind learning, these technologies allow you to
easily implement real-time servers and clients. If necessary you could run a
reverse proxy like nginx, so that your existing LAMP stack would get some
requests, and one or more NodeJS servers would get some.

This answer came out a bit fluffy, but I hope that it helps a little.. :-)

