我无法在WebSocket中启动闭包功能。所以,我编写的函数必须在每次触发套接字事件(ADD_USER)时增加一个计数器index
。但它没有发生......我错过了什么?
wss.on('connection', (ws) => {
let index = 0;
function indexInc() { // this one
return function() {
console.log(index); // ... does not invoke
return index += 1;
}
}
ws.on('message', (message) => {
const data = JSON.parse(message)
switch (data.type) {
case 'ADD_USER': {
indexInc() // does not start
users.push({ name: data.name, id: index})
ws.send(JSON.stringify({
type: 'USERS_LIST',
users
}))
broadcast({
type: 'USERS_LIST',
users
}, ws)
break
}