使用Socket.io向一个用户发送消息

时间:2017-08-07 01:21:44

标签: node.js redis socket.io

我正在寻找使用nodejs,socket.io,Redis向一个特定客户端发送消息的方法(这也意味着保留该用户的踪迹)

请帮助

修改

var app = require('express')();

var server = require('http').Server(app);
var io = require('socket.io')(server);
var redis = require('redis');
var user=[];

server.listen(3000);
io.on('connection', function (socket) {

    var redisClient = redis.createClient();
    redisClient.subscribe('message');

    user[socket.handshake.query.userid] = socket;

    socket.on('create', function(id) {
        user[id] = socket;
    });


    redisClient.on("message", function(channel, message) {
        var message=JSON.parse(message);
        var id=JSON.parse(message.id);
        var target=id;

        console.log("target id => "+user[target].id+" / socket.id => "+socket.id)

         try{
             if(user[target].id==socket.id){
                  user[target].emit(channel,message.msg);
              }else{
                  console.log('when socket.id dont match')
               }
         }catch (e){
             console.log(e);
         }
      console.log("\n#########################\n");

    });



});

1 个答案:

答案 0 :(得分:2)

确实,您需要存储传入连接。
客户端:

var userid = '69b6';//anything you like
var con = io.connect('localhost:4545/', { query: `userid=${userid}` });

服务器:

var users = {} ;
io.on('connection', function(client){
  users[client.handshake.query.userid] = client;
});

//you want to send something to a user
users[userid].emit('yolo', data);

编辑:我稍微改编了你的代码

var server = require('http').Server(app);
var io     = require('socket.io')(server);
var redis  = require('redis');
var users  = {};

server.listen(3000);

var redisClient = redis.createClient();

io.on('connection', function (socket) {
  var userId     = socket.handshake.query.userid;
  users[userId]  = socket;
});

redisClient.subscribe('message');
redisClient.on("message", function(channel, message) {
  var message     = JSON.parse(message);
  var userId      = message.id;
  var userSocket  = users[userId] || null;

  console.log('=======[Message received]=======');
  console.log('UserId:', userId);
  console.log('SocketId:', userSocket.id);

  if(userSocket){
    userSocket.emit(channel, message.msg);
    console.log("Message was succefully sent!");
  }else{
    console.log('User socket unavailable');
  }
});

告诉我它是否有效以及你是否难以理解我改变了什么。