我有一个应用程序,该应用程序使用websocket连接在页面加载后将一些数据发送到前端。我使用express的 locals 变量将websocket服务器传递到路由器。
这是套接字设置:
//certificate
var key = fs.readFileSync('encryption/cert.key');
var cert = fs.readFileSync('encryption/cert.pem');
var options = { key: key, cert: cert, passphrase: 'kevinius', requestCert: false, rejectUnauthorized: false };
//create server
const server = https.createServer(options, app).listen(process.env.PORT || 8080, (err)=>{
console.log(`Listening on: https://localhost:${process.env.PORT}`)
});
// websocket
let wss = new WebSocket({ server });
app.locals.socket = wss;
路由器设置:
router.get('/', function (req, res, next) {
var socket = req.app.locals.socket;
console.log('yesssssss')
socket.on('connection', (ws) => {
//this keeps on adding new eventListeners resulting in MaxListenersExceededWarning
console.log('connection');
ws.send(JSON.stringify(['cover', htmlTemplate]), (err) => {
//
});
})
}
但是,这导致在每次刷新新页面时添加多个eventListeners :
yesssssss
connection
yesssssss
connection
connection
yesssssss
connection
connection
connection
最终导致此错误::
(node:15515) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 message listeners added. Use emitter.setMaxListeners() to increase limit
那么我的设置中缺少什么?谢谢,
答案 0 :(得分:0)
好,我解决了...似乎我在概念上不了解websockets。
在路由器中,我删除了所有与Websocket相关的代码,并创建了一个模块,该模块在服务器启动时仅被调用一次。
server.js :
const sockLib = require('./library/ws.js');
sockLib.setConnection(server);
library / ws.js
const WebSocket = require('ws').Server;
var wss;
var socket;
function setConnection(server) {
wss = new WebSocket({ server });
wss.on('connection', (ws) => {
socket = ws;
socket.on('message', function (message) {
let mss = JSON.parse(message);
if (mss[0] == 'home/covers') {
callYourOtherCode(mss[1]);
}
});
})
}
module.exports.setConnection = setConnection;