user1354999
user1354999

Reputation: 163

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

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!

Upvotes: 6

Views: 1284

Answers (3)

chibisuke
chibisuke

Reputation: 51

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.

Upvotes: 5

Dave Kok
Dave Kok

Reputation: 912

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.

Upvotes: 1

Janus Troelsen
Janus Troelsen

Reputation: 21270

After the WebSocket handshake is done, it works pretty much like regular sockets. There is no reason why Apache would allow unidirectional communication without headers.

Upvotes: 0

Related Questions