非常感谢任何帮助!
背景:我正在构建一个由 Node.js 支持的网站,其中包含 WebSockets。我目前正在使用 websockets/ws图书馆。
愿望:我希望能够创建一些“包装器”发送函数,以便在我的每个套接字消息处理程序中更容易维护该功能,我是否应该选择更改它.这是我目前正在做的一些示例代码:
const wss = new ws.Server({
perMessageDeflate: false,
path: '/ws',
server: httpServer,
verifyClient: function() { /* doing stuff here for client verification */}
});
wss.on('connection', function onConnect(socket, request) {
// Using Lodash to extend the socket object to add the methods I need.
_.assignIn(socket, {
sendOk: function sendOk(message) {
return socket.send(JSON.stringify({
ok: true,
msg: message
}));
},
sendErr: function sendErr(message) {
return socket.send(JSON.stringify({
ok: false,
msg: message
}));
}
});
socket.on('message', function onIncomingMessage(message) {
try {
let jsonMessage = JSON.parse(message);
console.log('Successfully parsed incoming WebSocket message.');
return this.sendOk('Thanks for the update!');
}
catch (err) {
console.error('Error when parsing incoming WebSocket message.');
return this.sendErr('Your incoming message was not a JSON string.');
}
});
});
问题:使用这种方法,每次新用户连接到套接字(在初始握手之后)时,我都会扩展“套接字”对象,这会导致很多问题(例如用户可以在 Lodash 完成对象扩展之前连接并发送消息;服务器将遇到性能问题,因为该扩展是一项昂贵的操作;等等)。我需要能够在服务器启动时找到一种方法来执行此操作,以便在 WebSocket 服务器开始监听传入连接之前,所有传入套接字都已经包含我需要的方法。
最佳答案
Problems: With this approach, I am extending the "socket" object each time that a new user connects to the socket (after the initial handshake), which can cause so many problems (e.g. a user could connect and send a message before Lodash can complete the object extensions;
这不是真的。 Lodash 对象扩展是同步的,而 Javascript 是单线程的。因此,您没有机会在 connection
事件之后但在对象扩展就位之前处理事件。不可能发生。
the server will run into performance issues because that extension is an expensive operation; etc.). I need to be able to find a way to do this when the server is started, so that all incoming sockets will already contain the methods that I need before the WebSocket server has started listening for incoming connections.
扩展不是一个昂贵的操作。它只是为一个对象分配几个属性。很难将其与服务器性能相关的瓶颈联系起来。
如果您真的非常想避免在每个新连接上分配几个属性,您可以修改您的 webSocket 库使用的任何原型(prototype)。您可能必须检查该库的来源以确定原型(prototype)是什么以及您是否可以修改它。就我个人而言,我发现这比您现在所做的更脆弱,因为该原型(prototype)可能没有记录在案的界面方面。
通过向外部对象添加属性来扩展外部对象(您不直接调用其构造函数的对象)是一件非常合理的事情。这可能比向原型(prototype)添加内容更安全(从长期维护的 Angular 来看),除非您的对象的文档专门记录向原型(prototype)添加内容。甚至有可能该对象甚至不使用原型(prototype)(就像我说的,您必须查看代码以查看它是否使用以及您是否可以访问它)。
关于javascript - 从 "socket"库向 "websockets/ws"对象添加方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44999105/