Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebSocket server in PHP without daemons?

I will try to make my first post here as interesting as possible.

Lately I have been interested in the feasibility of handling WebSocket requests on a shared hosting server.

Please don't tell me "upgrade your plan". All this would be trivial on at least a VPS. I realize that.

As many know, shared hosts will...

  • Kill a daemon if they see one
  • Block usage of server sockets
  • Deny you shell access
  • Keep apache off limits (no module installations)

These restrictions eliminate phpwebsocket, python altogether. A no-daemon solution that masquerades as a web page is needed.

PHP being my favorite server-side language, I crafted a PHP websocket gateway posing as a web page.

So far I have been successful in sending the right headers for the handshake and streaming output (using output buffering), but I still can't figure out how to continue to read data after the initial request.

In short, I want to continue to receive data from the client even after the PHP script is started. I have tried reading the php://input pseudofile, but I can't seem to get any more reads out of it after the end of the GET. Is there any setting or hack that will allow this?

Thanks!

like image 460
user1354999 Avatar asked Apr 25 '12 01:04

user1354999


2 Answers

the short version: What you're trying to do is simply not possible.

the long version: the best you can get is a oneway communication channel that looks like a websocket connection in your browser, but that only works on one direction. From the server to the browser. The other direction will simply not work, because the webserver isn't aware that you're trying to use a different protocol than HTTP, and there is no way of telling it. At least not in the scenario you just outlined.

like image 73
chibisuke Avatar answered Nov 03 '22 16:11

chibisuke


Your problem here is Apache itself. Once Apache has read the first HTTP request (the websocket handshake) it will continue reading from the TCP connection for any additional HTTP requests. Thus any new data send on the TCP connection will never be passed on to your script. This is necessary as the HTTP/1.1 protocol supports Keep-Alive by default meaning multiple Request/Response cycles are done on one TCP connection. The browser doesn't open a HTTP connection for each request (which was the default in HTTP/1.0). You can't change this behavior. To implement a websocket server you will need to setup your own socket.

like image 38
Dave Kok Avatar answered Nov 03 '22 17:11

Dave Kok