要将其发送到当前连接的所有套接字,您需要跟踪当前连接的套接字,并将控制台功能的覆盖移动到connect事件之外,如下所示:
let activeSockets = new Set();
// override console functions
(function() {
const _privateLog = console.log;
const _privateError = console.error;
const _privateInfo = console.info;
const _privateWarn = console.warn;
const _privateDebug = console.debug;
function send(style, data) {
// send to all currently connected webSockets
if (typeof data === "object") {
data = JSON.stringify(data);
}
for (let ws of activeSockets) {
ws.send(`<span style="${style}">${data}</span>`);
}
}
console.log = function (message) {
send('color:lightgreen', message);
_privateLog.apply(console, arguments);
};
console.error = function (message) {
send('color:red', message);
_privateError.apply(console, arguments);
};
console.info = function (message) {
send('color:cyan', message);
_privateInfo.apply(console, arguments);
};
console.warn = function (message) {
send('color:yellow', message);
_privateWarn.apply(console, arguments);
};
console.debug = function (message) {
send('color:white', message);
_privateDebug.apply(console, arguments);
};
})();
wss.on('connection', function (ws) {
// maintain list of activeSockets
activeSockets.add(ws);
ws.on('close', function() {
activeSockets.delete(ws);
});
})