1. 后端部分 发送redis消息
可以参考此篇实现(直接使用Jedis即可)
http://www.cnblogs.com/binyue/p/4763352.html
2.后端部分: 接收redis消息
var redis;
if(process.argv.length <= 2){
redis = require('redis').createClient();
}else{
redis = require('redis').createClient(6379,process.argv[2]);
}
var io = require('socket.io').listen(5678);
var clients = {}
redis.subscribe('console');
redis.on('message', function(channel, data){
if (channel=="console"){
args = JSON.parse(data);
for(var s in clients){
clients[s].emit('event_' + args.id, args.message);
}
}
});
io.on('connection', function(socket){
var address = socket.request.connection.remoteAddress + ":" + socket.request.connection.remotePort
console.log(new Date() + ' client connected ['+ socket.id + "] " + address);
clients[socket.id] = socket;
socket.on('disconnect', function(){
console.log("discopnnect " + this.id + "-----" + this.request.connection.remoteAddress + ":" + this.request.connection.remotePort);
delete clients[socket.id];
});
socket.on('event', function(message){
});
});
package.json
{
"name" : "real-time",
"description" : "providing real-time message push for ",
"version" : "0.0.1",
"dependencies" : {
"socket.io" : "1.2.1",
"redis": "0.7.3",
"socket.io-client": "1.2.1"
}
}
前端部分 接收消息并显示
使用了 socket.io-1.0.6
var socket = io.connect(beeper_url);
socket.on('event_' + event_id,function(data){
callback(data);
})