jingxinxin / tiankeng

记录程序猿开发过程中已经遇到的各种坑,再记录解决方法 / Record the various pits that have been encountered during the development process, and then record the solution.
2 stars 0 forks source link

socket一些监听无响应,比如连接断掉后,socket.on('disconnect')没有效果 #12

Open jingxinxin opened 6 years ago

jingxinxin commented 6 years ago

问题复现情况之一

如下代码 在连接成功后先执行了类似await这样的异步等待操作,可能会导致socket.on('disconnect')未执行的问题

 io.on('connection', async socket => {
 ... 
       let res     = await sockets.find({id: socket.id)})

        await sockets.remove({id: socket.id})

        socket.on('private message', function (from, msg) {
            console.log('I received a private message by ', from, ' saying ', msg)
        })

        socket.on('disconnect', reason => {
            // console.log('下线:' + reason)
            delete wsUsers[query.id]
            socket.emit('onlineCount', io.eio.cliensCount)
        })
 ...
    })

调整一下它们的执行顺序,可以解决

  io.on('connection', async socket => {
 ...
        socket.on('private message', function (from, msg) {
            console.log('I received a private message by ', from, ' saying ', msg)
        })

        socket.on('disconnect', reason => {
            // console.log('下线:' + reason)
            delete wsUsers[query.id]
            socket.emit('onlineCount', io.eio.cliensCount)
        })

        let res     = await sockets.find({id: socket.id)})

        await sockets.remove({id: socket.id})
 ...
    })