【发布时间】:2020-08-05 11:33:23
【问题描述】:
我已经在 React、Node 和 Socket.io 上制作了聊天应用程序,每当我刷新我的页面或改变我的房间时,我都有额外的连接。如何关闭这个先前的连接以及如何管理它?我找到了 socket.leave() 和 socket.off() 但它对我不起作用:/ 提前致谢!
服务器端
let listOfRooms = [];
var allClients = [];
mongoose
.connect(
`mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASSWORD}@cluster0-lnoai.mongodb.net/${process.env.DB_NAME}?retryWrites=true&w=majority`
)
.then(() => {
io.on('connection',(socket)=>{
allClients.push(socket.id)
console.log(allClients);
socket.on('initRoom',({userData,roomList})=>{
listOfRooms = roomList;
listOfRooms.forEach(room=>{
const nsp = io.of(room.id);
nsp.on('connection', (nsSocket)=>{
nsSocket.on('joinRoom', ( data ) => {
const {userData, roomId} = data;
console.log(`joined to ${room.title}`);
});
nsSocket.on('sendMessage', (newMsg ) => {
const {roomId} = newMsg;
});
nsSocket.on('disconnect', () => {
console.log('disconnected nsSocket');
nsSocket.disconnect();
// removeUser(nsSocket.id)
// nsSocket.leaveAll(nsSocket.id);
})
});
})
})
})
})
.catch(err => {
console.log(err);
});
客户端
useEffect(() => {
socket = io(host);
const roomList = [];
namespaces.forEach((ns) => {
ns.rooms.forEach((room) => {
roomList.push(room);
});
});
socket.emit('initRoom', { userData, roomList });
}, []);
useEffect(() => {
const roomId = props.location.pathname.slice(1, props.location.pathname.length);
roomSocket = io(`${host}${roomId}`);
console.log(roomSocket);
const data = {userData, roomId}
roomSocket.emit('joinRoom', data);
return () =>{
roomSocket.emit('disconnect');
roomSocket.off()
socket.off()
}
}, [endpoint, props.location.pathname]);
useEffect(() => {
roomSocket.on('message', (message) => {
console.log('tu patrz');
const updatedMessages = [...messages, message];
setMessages(updatedMessages);
});
roomSocket.on('roomData', ({ users }) => {
setUsers(users);
console.log('users:');
console.log(users);
});
}, [messages, users]);
const sendMessage = (newMsg) => {
if (newMsg) {
const roomId = props.location.pathname.slice(1, props.location.pathname.length);
newMsg.roomId = roomId;
roomSocket.emit('sendMessage', newMsg);
setMessages('');
}
};
【问题讨论】: