Socket.io获取客户端的房间数(两次连接)

时间:2019-02-19 17:08:12

标签: javascript express socket.io

我是express.js和socket.io的新手,基本上我有一个简单的聊天页面,我的问题是我似乎无法使这个房间正常工作。每当有人进入/离开房间时,我想更新连接到特定房间的客户端数量,这是到目前为止我得到的:

客户

socket.on("connect", onConnect);
function onConnect() {
  socket.emit("join", "chat-room");
}
socket.on("disconnect", onDisconnect);
function onDisconnect() {
  socket.emit("leave", "chat-room");
}
socket.on("clientsCountResponse", data => {
  this.userCount = data;
});

服务器:

io.on('connection', (socket) => {

socket.on('join', (room) => {
    socket.join(room, (err) => {
        console.log('New Client joined room')
        io.to(room).emit('clientsCountResponse', io.engine.clientsCount)
    })
})

socket.on('leave', (room) => {
    socket.leave(room, (err) => {
        console.log('Client left room')
        io.to(room).emit('clientsCountResponse', io.engine.clientsCount)
    })
})

socket.on('newMessage', (msg) => {
    socket.broadcast.emit('newMessageResponse', msg)
})

socket.on('isTyping', (data) => {
    socket.broadcast.emit('isTypingResponse', data)
})

socket.on('isNotTyping', () => {
    socket.broadcast.emit('isNotTypingResponse')
})

})

我不知道事件何时触发,因为我得到的客户数量是随机的。 即使我不将它们发送到房间,newMessage Typing事件也运行良好。

编辑:好的,所以问题与逻辑无关,我遇到了双重连接问题,这是由于前端位置错误的io()初始化引起的

0 个答案:

没有答案