Is it possible to use Sockets.io on the client side and communicate with a PHP based application on the server? Does PHP even support such a 'long-lived connection' way of writing code?
All the sample code I find for socket.io seems to be for node.js on the server side, so no help there.
I was looking for a really simple way to get PHP to send a socket.io message to clients.
This doesn't require any additional PHP libraries - it just uses sockets.
Instead of trying to connect to the websocket interface like so many other solutions, just connect to the node.js server and use
.on('data')
to receive the message.Then,
socket.io
can forward it along to clients.Detect a connection from your PHP server in Node.js like this:
Here's the incredibly simple php code - I wrapped it in a function - you may come up with something better.
Note that
8080
is the port to my Node.js server - you may want to change.You can use it like this:
sio_message("chat message","Hello from PHP!");
You can also send arrays which are converted to json and passed along to clients.
sio_message("DataUpdate",Array("Data1" => "something", "Data2" => "something else"));
This is a useful way to "trust" that your clients are getting legitimate messages from the server.
You can also have PHP pass along database updates without having hundreds of clients query the database.
I wish I'd found this sooner - hope this helps!
UPDATE: Aug 2014 The current socket.io v1.0 site has a PHP example:- https://github.com/rase-/socket.io-php-emitter
If you really want to use PHP as your backend for WebSockets, these links can get you on your way:
https://github.com/lemmingzshadow/php-websocket
http://www.htmlgoodies.com/html5/other/create-a-bi-directional-connection-to-a-php-server-using-html5-websockets.html#fbid=QqpDVi8FqD9
How about this ? PHPSocketio ?? It is a socket.io php server side alternative. The event loop is based on pecl event extension. Though haven't tried it myself till now.
Erm, why would you want to? Leave PHP on the backend and NodeJS/Sockets to do its non-blocking thing.
Here is something to get you started: http://groups.google.com/group/socket_io/browse_thread/thread/74a76896d2b72ccc
Personally I have express running with an endpoint that is listening expressly for interaction from PHP.
For example, if I have sent a user an email, I want socket.io to display a real-time notification to the user.
Want interaction from socket.io to php, well you can just do something like this:
Seriously, PHP is great for doing server side stuff and let it be with the connections it has no place in this domain now. Why do anything long-polling when you have websockets or flashsockets.
If you really want to use PHP as your backend for socket.io ,here are what I found. Two socket.io php server side alternative.
https://github.com/walkor/phpsocket.io
https://github.com/RickySu/phpsocket.io
Exmaple codes for the first repository like this.