我通常使用一个数组来存储套接字服务器中的所有连接客户端,但这次我决定稍微调整一下并使用对象而不是数组。也许这是我最近的一个项目的问题,但这是我运行的一个接近的模型,它几乎总是有效,但是偶尔getusername()将返回null。我想知道为什么,而且我还包括这种行为偶尔会导致服务器崩溃的地方。
const express = require(`express`);
const http = require(`http`);
const ioserver = require(`socket.io`);
const app = express();
const server = http.Server(app);
const io = ioserver(server);
let sessions = {};
io.sockets.on('connection', socket =>{
socket.on('login', (data)=>login(socket, db, data));
socket.on('eventafterloggingin', (data)=>eventafterloggingin(socket, data));
socket.on('disconnect', ()=>disconnect(socket));
});
const getusername = socket => {
return Object.keys(sessions).find(key => sessions[key] === socket);
}
const login = (socket, db, data)=>{
//do a bunch of sanitization, db querying, data validation, etc
//...
//...
//if all passes through:
sessions[res.username] = socket;
socket.emit('dootherthings');
}
const eventafterloggingin = (socket, data)=>{
const username = getusername(socket);
sessions[username].emit('eventthatbreaksserver'); //sessions[username] sometimes will be null ?????
}
const disconnect = socket => {
for(let user in sessions){
if (socket == sessions[user]){
delete sessions[user];
break;
}
}
}
当试图将这个死套接字与emit一起使用时的堆栈跟踪:
2018-02-22T04:59:07.273286+00:00 app[web.1]: /app/app.js:117
2018-02-22T04:59:07.273300+00:00 app[web.1]: sessions[username].emit('eventthatbreaksserver');
2018-02-22T04:59:07.273303+00:00 app[web.1]: ^
2018-02-22T04:59:07.273305+00:00 app[web.1]:
2018-02-22T04:59:07.273307+00:00 app[web.1]: TypeError: Cannot read property 'emit' of undefined
2018-02-22T04:59:07.273315+00:00 app[web.1]: at /app/node_modules/socket.io/lib/socket.js:513:12
2018-02-22T04:59:07.273310+00:00 app[web.1]: at eventafterloggingin (/app/app.js:117:30)
2018-02-22T04:59:07.273312+00:00 app[web.1]: at Socket.socket.on (/app/app.js:40:30)
2018-02-22T04:59:07.273313+00:00 app[web.1]: at Socket.emit (events.js:159:13)
2018-02-22T04:59:07.273317+00:00 app[web.1]: at _combinedTickCallback (internal/process/next_tick.js:131:7)
2018-02-22T04:59:07.273319+00:00 app[web.1]: at process._tickCallback (internal/process/next_tick.js:180:9)