Answer the question
In order to leave comments, you need to log in
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});
});
});
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);
});
});
[ { 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 } ]
Answer the question
In order to leave comments, you need to log in
Is it not desirable to indicate the room identifier in the message?
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 questionAsk a Question
731 491 924 answers to any question