我对Socket.io有点陌生。但是我建立了一个聊天室,用户可以在其中更改房间。问题是当用户更改房间时,所有其他用户也都更改到同一房间。我不确定自己做错了什么。谁能解释我的代码有什么问题?聊天已在Angular应用中使用。聊天由Express托管。
let express = require('express');
let app = express();
let http = require('http');
let server = http.Server(app);
let usercount = 0;
let socketIO = require('socket.io');
let io = socketIO(server);
const port = process.env.PORT || 3000;
io.on('connection', (socket) => {
usercount++;
console.log(usercount.toString());
socket.on('join-main-chat', (message) => {
socket.join('main room');
io.to('main room').emit('new-message', usercount.toString());
});
socket.on('change-room', (message) => {
newRoom = message;
socket.leaveAll();
socket.join(newRoom);
console.log("new room might be: " + message);
socket.join(message);
});
socket.on('new-message', (message) => {
console.log(message);
io.emit('new-message', message);
io.emit('get-count', usercount.toString());
});
socket.on('left-message', (message) => {
usercount--;
console.log(usercount.toString());
io.emit('new-message', message);
io.emit('new-message', usercount.toString());
io.emit('get-count', usercount.toString());
});
});
server.listen(port, () => {
console.log(`started on port: ${port}`);
});