根据您的示例,APP将为每个用户打开一个新的redis连接,这没有意义.
这对于整个应用程序使用一个连接(您必须再为连接作业发布数据)
客户端
var socket = io.connect('http://localhost:3000'); socket.emit('channel','US'); socket.on('news',function(news){ $("body").append('
' + news); }); socket.on('message',function(msg){ $("body").append('
' + msg); });
服务器端
var io = require('socket.io'); var express = require('express'); var app = express.createServer(); io = io.listen(app); app.listen('3000'); var pub = require('node_redis').createClient(); //publish cli var redis = require('node_redis').createClient(); //sub cli redis.psubscribe('*'); redis.on('pmessage',function(pat,ch,msg){ io.sockets.in(ch).emit('news',msg); }); io.sockets.on('connection',function(socket){ console.log('Socket connected: ' + socket.id); socket.on('channel',function(ch){ socket.join(ch) //Publishing data on ch pub.publish(ch,"Hello " + ch); }); socket.on('disconnect',function(){ console.log('Socket dis connected: ' + socket.id); }); }); console.log('Server started @ 3000');