Just to elaborate a bit on why Apache + PHP is unsuitable for WebSocket support...
1) Do we need to use some 3rd Party APIs or Libraries like Ratchet, PHP-Push-WebSocket or PHP WebSocket to enable PHP to communicate over WebSocket protocol?
No, you can just open a local socket and accept requests using low-level Socket API (example), or you can even upgrade an existing request to WebSocket. But there is a problem - read on...
2) If your answer to above question is yes then what is the advantage/purpose of using Apache's mod_proxy_wstunnel
?
The advantage of mod_proxy_wstunnel
is that it allows users to establish WebSocket connections with your server using the server's HTTP(S) port (usually 80 or 443) instead of connecting on a custom port (e.g. 9000). This does not eliminate step 1 though, as it simply proxies WebSocket connections from Apache to the custom port.
3) If I use any PHP WebSocket 3rd Party Library, then do I still need to enable and use Apache's mod_proxy_wstunnel?
The problem with Apache / PHP setup is that PHP code always runs in scope of a specific HTTP request. This is a problem because Apache is not designed for long-running requests. Apache can support a very small amount of active requests (usually 150 or so), which is barely enough to handle regular (short-lived) traffic on an medium-size site. In addition, by default max_execution_time
is set to 5 minutes, which means any request (and any WebSocket connection inside of it) will be killed after that.
If No, then again what is the purpose of Apache's mod_proxy_wstunnel
?
mod_proxy_wstunnel
handles persistent connections without tying up a request thread. So it allows one Apache instance to handle hundreds of thousands of WebSocket connections. But again, it's just a tunnel, it can't "invoke" PHP, as it can only proxy a WebSocket connection to some other application.
If you have access to the server machine, you can run a standalone PHP script, which would handle WebSocket connections as a daemon outside Apache (e.g. via systemd), and optionally use mod_proxy_wstunnel
to proxy requests to it.
But by itself, Apache + PHP architecture is unsuitable for production-grade WebSocket support.