Socket.io 1.0.0 ^: Using the default room instead of the user room for custom messages

socket.io 1.4.5, node.js 5.x

Go ahead: there has been a lot of reading, effort and failure before this post, so I hope this helps many future readers.


The possibility of using the default room confused me when I consider how to use the rooms to communicate with a specific user (for example, a direct message)

Because intuitively, it looks like a ready-made solution that should potentially discount the need to create a custom room for each user using userID or email, for example, this is a popular solution .

And since it was created automatically, I decided that it should be mine and only a unique listener for each user.

What role do I consider my due diligence to create this solution:

io.on('connection', function(socket){
  var curretUserID = null

  socket.on('set user',function(user){
    userID = curretUserID.id
  });

  io.to(socket.id).emit('welcome','welcome to the room!)

  socket.on('chat message', function(msg){//Makes Sense
    io.emit('chat message', msg);
  });

  socket.on('private message', function(id, msgData){
    if(userID === msg.recipientID){
        socket.to(id).emit('private message', 'for your eyes only');
    }
  });

});

I installed userIDin order to live inside the parent area connectionto avoid the need to create a map between users and sockets, because presumably this should be the advantage of using the solution for the room as a whole.

Now I didn’t see anyone doing it this way, so I have no idea completely directing a direction not intended for the default rooms, or if for some reason this does not scale or work well in the wild.

Question:

( , ) ?

+4
1

, ... .

, . Socket.io socket.id. , , socket.id 4zIISeXsSvKL6VGyAABe, - /#4zIISeXsSvKL6VGyAABe.

, socket.io , .

, user.id .

:

io.on('connection', function(socket) {
  socket.emit('register id', socket.id)
}

:

socket.on('register id', function(id){
  socket.id = id
})

:

io.on('connection', function(
  socket.emit('register id', socket.id)

  io.to(socket.id).emit('welcome','welcome to the room!)

  socket.on('chat message', function(msg){//Makes Sense
    io.emit('chat message', msg);
  });

  socket.on('private message', function(msgData){
        socket.to(msg.recipientID).emit('private message', 'for your eyes only');
  });

});
+1

Source: https://habr.com/ru/post/1628043/


All Articles