简体   繁体   中英

How to emit event to same user which is opened in different tabs or browser in socket.io?

i found by creating room it can be executed..but some where something is wrong.

serverside:-

var app = require('express')();
var http = require('http').Server(app);
var io   =  require('socket.io')(http);
var users = {};
var rooms = [];


http.listen(3000, function(){
  console.log('listening on *:3000');
});

io.on('connection', function(socket){

 socket.on('Init', function(data){
  if(data in users){

   var roomName = 'room'+ data;
   var index = rooms.indexof(roomName);
   if(rooms.notContain(roomName)){
    rooms.push(roomName);
   var index = rooms.indexof(roomName);
    users[data].join(rooms[index]);
    socket.join(rooms[index]);
   }else{
    socket.join(rooms[index]);
   }
  }else{
   socket.username = data;
   users[socket.username] = socket;
  }

  var indo = rooms.indexof('room'+ data);
  socket.in(rooms[indo]).emit('hai', data);
 });
});

Array.prototype.indexof = function(Obj){
 return this.indexOf(Obj);
}
Array.prototype.notContain = function(Obj){
 for(i in this){
  if(this[i] === Obj) return false;
 }
 return true;
}

Client Side:-

var socket = io.connect('http://localhost:3000', { 'forceNew': true});
var userId = '<?php echo $_GET['userId'] ?>';
socket.on('connect', function(){
 socket.emit('Init', userId);
});
socket.on('hai', function(data){
 alert(data);
});

Please check this or get me any other solution to solve this issue. I want same user to emit which is opened in different browser or tabs.

I'm guessing you're trying to send a message to all connections which are the same user. Here is one way to do that:

var user_sockets = {};
io.on('connection', function(socket){
 socket.on('Init', function(data){
  if (typeof user_sockets[data] === 'undefined') {
    user_sockets[data] = [];
  }

  user_sockets[data].push(socket);
  for (var i = 0; i < user_sockets[data].length; i++) {
    var s = user_sockets[data][i];
    s.emit('hai', data);
  }
 });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM