How Can a LAMP Guy Easily Implement WebSockets? - php

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. 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!

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.. :-)

Related

Stateless & asynchronous web-server with PHP (and Symfony)

TL;DR: I'm not sure this topic has its place on StackOverflow, but basically it's just a topic of debate and thinking about making PHP apps like we would do with NodeJS for example (stateless request flow, asynchronous calls, etc.)
The situation
We know NodeJS can be used as both a web-server and web-app.
But for PHP, the internal web-server is not recommended for production (so says the documentation).
But, as Symfony full-stack is based on the Kernel which handles Request objects, it means we should be able to send lots of requests to the same kernel, only if we could "bootstrap" the php web-server (not the app) by creating a kernel before listening to HTTP requests. And our router would only create a Request object and make the kernel handle it.
But for this, a Symfony app has to be stateless, for example we need Doctrine to effectively clear its unit of work after a request, or maybe we would need to sort of isolate some components based on a request (By identifying a request with its unique PHP class reference id? Or by using other php processes?), and obviously, we would need more asynchronous things in PHP or in the way we use the internal web-server.
The main questions I sometimes ask myself, and now ask to the community
To clarify this, I have some questions about PHP:
Why exactly is the internal PHP webserver not recommended for production?
I mean, if we can configure how the server is run and its "router" file, we should be able to use it like any PHP server, yes or no?
How does it behaves internally? Is memory shared between two requests?
By using the router, it seems obvious to me that variables are not shared, else we could make nodejs-like apps, but it seems PHP is not capable of doing something like this.
Is it really possible to make a full-stateless application with Symfony?
e.g. I send two different requests to the same kernel object, in this case, is there any possibility that the two requests create a conflict in Symfony core components?
Actually, the idea of "Create a kernel -> start server -> on request, make the kernel handle it" behavior would be awesome, because it would be something quite similar to NodeJS, but actually, the PHP paradigm is not compatible with this because we would need each request to be handled asynchronously. But if a kernel and its container is stateless, then, there should be a way to do something like that, shouldn't it?
Some thoughts
I've heard about React PHP, Ratchet PHP for Websocket integration, Icicle, PHP-PM but never experienced them, it seems a bit too complex to me for now (I may lack some concepts about asynchronicity in apps, that's why my brain won't understand until I have some more answers :D ).
Is there any way that these libraries could be used as "wrappers" for our kernel request handling?
I mean, let's create this reactphp/icicle/whatever environment setup, create our kernel like we would do in any Symfony app, and run the app as web-server, and when a request is retrieved, we send it asynchrously to our kernel, and as long as the kernel has not sent the response, the client waits for it, even if the response is also sent asynchrously (from nested callbacks, etc., like in NodeJS).
This would make any existing Symfony app compatible with this paradigm, as long as the app is stateless, obviously. (if the app config changes based on a request, there's a paradigm issue in the app itself...)
Is it even a possible reality with PHP libraries rather than using PHP internal web-server in another way?
Why ask these questions?
Actually, it would be kind of a revolution if PHP could implement real asynchronous stuff internally, like Javascript has, but this would also has a big impact on performances in PHP, because of persistent data in our web-server, less bootstraping (require autoloader, instantiate kernel, get heavy things from cached files, resolve routing, etc.).
In my thoughts, only the $kernel->handleRaw($request); would consume CPU, the whole rest (container, parameters, services, etc.) would be already in the memory, or, for the case of services, "awaiting to be instantiated". Then, performance boost, I think.
And it may troll a bit the people who still think PHP is a very bad and slow language to use :D
For readers and responders ;)
If a core PHP contributor reads me, is there any way that internally PHP could be more asynchronous even with a specific new internal API based on functions or classes?
I'm not a pro of all of these concepts, and I hope really good experts are going to read this and answer me!
It could be a great advance in the PHP world if all of this was possible in any way.
Why exactly is the internal PHP webserver not recommended for
production? I mean, if we can configure how the server is run and its
"router" file, we should be able to use it like any PHP server, yes or
no?
Because it's not written to behave well under load, and there are no configuration options that let you handle HTTP request processing before it reaches PHP.
Basically, it lacks features if you compare it to nginx. It would be equal to comparing a skateboard to a Lamborghini.
It can get you from A to B but.. you get the gist.
How does it behaves internally? Is memory shared between two requests?
By using the router, it seems obvious to me that variables are not
shared, else we could make nodejs-like apps, but it seems PHP is not
capable of doing something like this.
Documentation states it's singlethreaded, so it appears that it would behave the same as if you wrote while(true) { // all your processing here }.
It's a playtoy designed to quickly check a few things if you can't be bothered to set up a proper web server before trying out your code.
Is it really possible to make a full-stateless application with
Symfony? e.g. I send two different requests to the same kernel object,
in this case, is there any possibility that the two requests create a
conflict in Symfony core components?
Why would it go to the same kernel object? Why not design your app in such a way that it's not relevant which object or even processing server gets the request? Why not design for redundancy and high availability from the get go? HTTP = stateless by default. Your task = make it irrelevant what processes the request. It's not difficult to do so, if you avoid coupling with the actual processing server (example: don't store sessions to local filesystem etc.)
Actually, the idea of "Create a kernel -> start server -> on request,
make the kernel handle it" behavior would be awesome, because it would
be something quite similar to NodeJS, but actually, the PHP paradigm
is not compatible with this because we would need each request to be
handled asynchronously. But if a kernel and its container is
stateless, then, there should be a way to do something like that,
shouldn't it?
Actually, nginx + php-fpm behave almost identical to node.js.
nginx uses a reactor to handle all connections on the same thread. Node.js does the exact same thing. What you do is create a closure / callback that is fed into Node's libraries and I/O is handled in a threaded environment. Multithreading is abstracted from you (related to I/O, not CPU). That's why you can experience that Node.js blocks when it's asked to do a CPU intensive task.
nginx implements the exact same concept, except this callback isn't a closure written in javascript. It's a callback that expects an answer from php-fpm during <timeout> seconds. Nginx takes care of async for you. What your task is is to write what you want in PHP. Now, if you're reading a huge file, then async code in your PHP would make sense, except it's not really needed.
With nginx and sending off requests for processing to a fastcgi worker, scaling becomes trivial. For example, let's assume that 1 PHP machine isn't enough to deal with the amount of requests you're dealing with. No problem, add more machines to nginx's pool.
This is taken from nginx docs:
upstream backend {
server backend1.example.com weight=5;
server backend2.example.com:8080;
server unix:/tmp/backend3;
server backup1.example.com:8080 backup;
server backup2.example.com:8080 backup;
}
server {
location / {
proxy_pass http://backend;
}
}
You define a pool of servers and then assign various weights / proxying options related to balancing how requests are handled.
However, the important part is that you can add more servers to cope with availability requirements.
This is the reason why nginx + php-fpm stack is appealing. Since nginx acts as a proxy, it can proxy requests to node.js as well, letting you handle web socket related operations in node.js (which, in turn, can perform an HTTP request to a PHP endpoint, allowing you to contain your entire app logic in PHP).
I know this answer might not be what you're after, but what I wanted to highlight is the way node.js works (conceptually) is identical to what nginx does when it comes to handling incoming request. You could make php work as node does, but there's no need for that.
Your questions can be summed up as this:
"Could PHP be more like Node?"
to which the answer is of course "Yes." But that leads us to another question:
"Should PHP be more like Node?"
and now the answer is not that obvious.
Of course in theory PHP could be made more like Node - even to a point to make it exactly the same. Just take the next version of Node and call it PHP 6.0 or something.
I would argue that it would be harmful to both Node and PHP. There is a diversity in the runtime environments for a reason. One of the variations is the concurrency model used in a given environment. Making one like the other would mean less choice for the programmer. And less choice is less freedom of expression.
PHP and Node were created in different times and for different reasons.
PHP was developed in 1995 and the name stood for Personal Home Page. The use case was to add some server-side dynamic features to HTML. We already had SSI and CGI at that point but people wanted to be able to inject right into the HTML - synchronously, as it wouldn't make much sense otherwise - results of database queries and other computations. It isn't a surprise how good it is at this job even today.
Node, on the other hand, was developed in 2009 - almost 15 years later - to create high performance network servers. So it shouldn't surprise us that writing such servers in Node is easy and that they have great performance characteristics. This is why Node was created in the first place. One of the choices it had to make was a 100% non-blocking environment of single-threaded, asynchronous event loops.
Now, single-threading concurrency is conceptually more difficult than multi-threading. But if you want performance for I/O-heavy operations then currently you have no other options. You will not be able to create 10,000 threads but you can easily handle 10,000 connections with Node in a single thread. There is a reason why nginx is single-threaded and why Redis is single threaded. And one common characteristic of nginx and Redis is amazing performance - but both of those were hard to write.
Now, as far as Node and PHP go, those technologies are so far from each other that it's hard to even comprehend how their fusion would look like. It reminds me the old April Fool's joke about unifying Perl and Python that so many people believed in.
PHP has its strengths and Node has it strengths. And just like it would be hard to imagine Node with blocking-I/O, it would be equally hard to imagine PHP with non-blocking I/O.
To summarize: it could be possible to make PHP like Node, but I wouldn't expect it to happen any time soon - if ever.

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!
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

socket.io + php + is this a realistic solution at this point in time

I have been reading about websockets and also about socket.io.
I understand websockets are not support but enough browsers yet to be realistically used.
socket.io has browser support but appears to need node.js. With my hosting solution I have some space on a shared server, very limited control over the server and have access to php but there is no node.js.
I have read that people can get socket.io to work with PHP.
Question: seeing I have very limited server access, not control over ports, command line etc is it realistic that I could get socket.io working with PHP or should I just stick with the AJAX calls (I'm currently using)?
Note: I've developed a chat solution and it appears it would be much more light weight if it was running with a socket solution.
Also - is there good security with Sockets.io?
thx
Trying to make PHP talk to socket.io I suspect will be a big task.
Certainly it's not a great idea to run websockets via a pre-fork or threaded apache. Any event based server should be OK if you can handle the number of PHP processes. A better approach would be to write an event based server in php. Like this one
i researched a few websocket server implementations. i read, that there is a way to use node.js in production. using apache many years, i also searched for a module to handle websockets within apache, but found only half-hearted stuff. nothing which seemed solid.
i stumbled upon yaws, which is a websocket capable server written in erlang, which has the advantages of beeing the right language for a highly parallel application such as the chat thing, and also because websockets should be well integrated within the main server.
now, i'm developing a php chat server, which uses a framework called ratchet. -> google for 'ratchet php'. they got a good tutorial.
i start it via the commandline, and although for you it should be possible to also start the ratchet server via a browser call, i would not recommend that.
so in your constrained hosting environment, i would stick to ajax.

PHP sockets - what do I need to work with them?

Only yesterday, I was asking a friend of mine how he would go about emulating direct communication channels between two clients through a web server, for the purpose of creating a chat application, but by using solely PHP/MySQL/JavaScript.
He told me that the best way to do this was by the use of SOCKETS, a term I had only heard of until then. This morning I started looking into it for the purpose of creating my chat application, but I'm quickly starting to believe that it's not as easy as I'd hoped.
So my question is this: if I don't have access to my own server (I have a domain hosted on a shared server that I also use for testing purposes), can I still use sockets to achieve my goal? If so, how exactly? (Please understand that I am completely new to the idea)
If not, what other way is there to accomplish the communication channels?
My only idea so far is to simply send periodic requests (AJAX) to the web server the application would be stored on and request any new messages, if any. But this does not seem very feasible.
Thanks in advance for your help!
I think what your friend is trying to get to is implementing Comet for your chat site.
Assuming he's getting you to use PHP sockets to act as a daemon, I highly doubt a shared hosting provider will let you do it.
You could try hanging the PHP script until there's data available. However, this will quickly consume resources on a CGI-based server since the PHP server can't tell if the client is still connected. I know this from experience.
For these kind of things, I highly recommend you get a dedicated server or VPS and write your backend in something like socket.io which automagically handles all your communication problems on both the client and server side. PHP, MYSQL and servers that fork to serve requests are usually the worst case scenarios for implementing Comet since they incur quite a bit of overhead and aren't scalable.
If you can't afford to run your own Comet server, then polling may be your only option. This will be the most resource intensive and least responsive.

Help creating a streaming (or push) API with PHP and Apache

I'd like to create an API for a project I'm working on, allowing developers to create desktop and mobile applications built around its functionality. One thing I've always wanted to learn how to do is create a stateless, push notification system, similar to Twitter's Streaming API.
Basically, I want to be able to notify users of any changes to the data in real time, or as close to it as possible. I know that this might be difficult on mobile devices, which is why mobile applications will probably be built to check for updates periodically, to save battery. However, desktop applications won't have that limitation. I'd like to avoid making the application ask the server if there is new information, and instead let the server tell the application that there is new data.
My programming language is PHP and my server is Apache. If I absolutely had to I could switch to Lighttpd or nginx, but that's an absolute last resort since it would require a lot of changes to all of my existing code.
I've read this article:
http://www.zeitoun.net/articles/comet_and_php/start
And tested it out, but unfortunately all that happens is my browser keeps attempting to load the page and never actually displays the time. I suspect this is because, for whatever reason, I've never been able to get output buffering to work on my server, unless I send 64kb (or more) of data. I heard that I had to disable gzip, which I did, and it still didn't work, so I don't know.
Have a look at some existing technologies to help you do this:
Tornado
Tornado is an open source version of the scalable, non-blocking web server and tools that power FriendFeed. The FriendFeed application is written using a web framework that looks a bit like web.py or Google's webapp, but with additional tools and optimizations to take advantage of the underlying non-blocking infrastructure.
Pusher
Pusher is a hosted API for quickly, easily and securely adding scalable realtime functionality via WebSockets to web and mobile apps.
Both are extremely fast and scalable, and I have setup both relatively easily.
Well you could do this in several ways, you could build in a poller at the client side, or you could use something like NodeJS. (http://nodejs.org/) or web sockets.
Yeah another good piece is
http://socket.io/
and
http://elephant.io/
some tuorials like this might also be useful.
http://www.phpbuilder.com/articles/application-architecture/optimization/creating-real-time-applications-with-php-and-websockets.html

Categories