zoukankan      html  css  js  c++  java
  • nodejs+socketio+redis实现前端消息实时推送

    nodejs+socketio+redis实现前端消息实时推送

    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);
    })
  • 相关阅读:
    概率论
    计算机网络基础
    数据库 数据库管理系统 数据库系统
    第二次冲刺总结
    Beta版总结会议
    Beta阶段项目总结
    beta版本“足够好”/测试矩阵
    zencart批量更新后台邮箱地址sql
    php首页定向到内页代码
    用.htaccess 禁止IP访问
  • 原文地址:https://www.cnblogs.com/fangyuan303687320/p/5742735.html
Copyright © 2011-2022 走看看