Look at the main parts of App.js first.
Io.sockets.on (' Connection ', function (socket) {var Credis = redis.createclient ();
Credis.auth (' Chenqiguo ');
Subscribe to a channel Redis link var subscribe = redis.createclient (); Subscribe.auth (' Chenqiguo ');
Authorize//Create a Redis link to the posting message, send a message to the specified channel var publish = Redis.createclient ();
Publish.auth (' Chenqiguo ');/authorized//socket Listener The Publisher publishes a message on a channel socket.on (' Publish ', function (channel,data) {
Publish.publish (Channel,data); //scoket Listener subscribers subscribe to a channel socket.on (' Psubscribe ', function (channel,username) {credis.sadd (' User: ' +username,channel ');
Here we put the user each subscription channel into a set of Subscribe.psubscribe (channel);
}//server accepts page disconnects after channel (Redis single Connection problem) Socket.on (' Psuballscribe ', function (channelarr,username) {
for (Var i=0;i<channelarr.length;i++) {subscribe.psubscribe (channelarr[i]);(Pattern,channel,message)
{socket.emit (' message ', {channel:channel,data:message})}) })
Here is the Index.js section:
Exports.index = function (req, res) {
var username = req.session.username;
var Redis = require (' Redis '). CreateClient ();
Redis.auth (' Chenqiguo ');
Redis.smembers (' User: ' +username,function (err,results) {
//Get all channel to the current user subscription to the template
res.render (' index ', { Title: ' Express ', username:username,result:results})
;}; This allows only logged-in users to receive and post messages (showing that this is not good, but for practical purposes)
Exports.login = function (req,res) {
var username = Req.body.username;
if (username!= ') {
req.session.username = Username;
Res.redirect ('/');
}
Here's the Index.ejs section.
<!doctype html>