Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Redis to communicate between PHP and socket.io/node.js

I have a PHP app built and running on Apache, using Nginx as a reverse proxy to serve static resources.

I also have Redis installed which I am using to store activity ID's for each users activity stream. The activity gets written to a MySQL database, then Redis pushes the activity ID into each users stream. When a user receives his/her activity stream, the app first retrieves the users list of activity ID's from Redis and then gets the actual activity data via a MySQL IN() query.

This all works very well, however I want to start add real time capability to this set up. I would like to be able to push these events straight to a users browser and also add general live notifications.

For this I have installed node.js with socket.io. I have the socket.io server correctly up and running and a client is automatically connected on page load.

Where I am struggling is in understanding how to post a message to socket.io from within my PHP app. Since PHP and node.js cannot communicate directly, my understanding is that I would be best off utilizing Redis as a go-between since I already have it installed and up and running. However I have no idea how to go about this.

What I need is a description of the process (any code examples would be very helpful) of sending a notification from PHP to Redis and then into socket.io in order for it to be pushed to the relevant client.

Also, I do not understand how socket.io would know which client to send to. How would I pass this information along and keep everything synced? Is this even necessary? Do I need to store my PHP sessions in Redis and have socket.io collect the data when a user connects? Or is there another way?

Thanks in advance.

Please Note: My PHP SESSION data is currently saved to disk.

like image 987
gordyr Avatar asked May 10 '13 11:05

gordyr


1 Answers

You can set up a pubsub channel on Redis (please see http://redis.io/topics/pubsub). Then subscribe to it from your node.js process. Your PHP would then publish to pubsub to communicate to the node. You can have separate pubsub channels for different clients and publish to whatever channels you need to reach your specific clients.

like image 192
akonsu Avatar answered Oct 19 '22 10:10

akonsu