L
L
lavezzi12018-10-23 18:42:56
JavaScript
lavezzi1, 2018-10-23 18:42:56

Many channels/rooms at the same time on socket.io?

Hello. I understand socket.io, I write chat like slack or discord. Where the user is connected to multiple rooms/channels. I studied the dock and a bunch of tutorials, found a lot of examples with chats, but they are all rather primitive. With the help of rooms it is impossible to implement, because when connecting and joining, the user has the same socket.id for all rooms and when emitting a message from the server, it gets to all rooms. In this case, the meaning of rooms is not entirely clear.
Perhaps I should use namespaces? What am I doing wrong?
UPD:
client

const rooms = [{...}, {...}];
this.socket.on('connect', () => {
   rooms.forEach((room) => {
     this.socket.emit('join', {user, room});
   });
});

server
io.on('connection', (socket) => {
  console.log('New user connected');

  // Join
  socket.on('join', ({ user, room }) => {

    socket.join(room.id);
    users.removeUser(`${user.name}_${room.id}`);
    users.addUser(`${user.name}_${room.id}`, user.name, room.id);
  });

  // Chatting
  socket.on('message', async ({user, room, message}) => {
    await db.query('INSERT INTO messages SET ?', { userId: user.id, roomId: room.id, text: message});
    socket.broadcast.to(room.id).emit('message', { room, user, text: message });
  });

  socket.on('disconnect', () => {
    users.removeUser(socket.id);
  });
});

Here is a list of users after the connection:
[ { id: 'Pavel_1', name: 'Pavel', room: 1 },
     { id: 'Max_1', name: 'Max', room: 1 },
     { id: 'Max_2', name: 'Max', room: 2 },
     { id: 'Pavel_2', name: 'Pavel', room: 2 } ]

When sending a message from Pavel to room 2, the message arrives in all rooms. It turns out that I need to check on the client when I listen to new messages, if it has arrived from the current room, then show the message? Then it is not clear why rooms are needed.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan Shumov, 2018-10-23
@inoise

Is it not desirable to indicate the room identifier in the message?

V
Vitaly, 2018-10-23
@vshvydky

buddy, you didn’t get the doc,
see how to solve it, hang up

io.on('connection', function (socket) {
  socket.on('join', function (from, msg) { ожидаем с клиента emit('join', 'channame')
    socket.join(msg); // msg = channame
    socket.to(msg).emit(`client ${from} connect to chat`);
  });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question