Socket.IO手动“断开”和var范围的发射?

时间:2017-10-06 19:31:02

标签: javascript node.js sockets socket.io network-programming

有人可以解释断开连接是如何工作的吗?

在我的控制台日志中,当客户端离开游戏时,会断开断开连接功能两次。为什么是这样?当它发生时,似乎在第二次调用时也知道了playerName的范围,但不是第一次调用。这些电话是同一个客户吗?另外,它如何知道该范围内的playerName,但在send-message中它不知道什么是playerName? (1是玩家名称)

Oct 06 11:57:36 overwatchtracker app/web.1: [RECV] Player disconnected: 1 
Oct 06 11:57:36 overwatchtracker app/web.1: [RECV] Player disconnected: undefined
Oct 06 11:57:29 overwatchtracker app/web.1: [RECV] Message: undefined asdfasdf 

以下是我的一些代码:

const io = socketIO(server)
var clients = []
io.on('connection', (socket) => {
    var playerName;
    socket.on('login-user', (name) => {
        playerName = name
    })
    socket.on('send-message', (message) => {
        socket.broadcast.emit('send-message', playerName, message)
    })
    socket.on('disconnect', () => {
        socket.broadcast.emit('player-disconnected', playerName)
        for (var i = 0; i < clients.length; i++) {
            if (clients[i].name == playerName) {
                clients.splice(i, 1)
            }
        }
    })
)}

0 个答案:

没有答案