Home > OS >  Storing custom objects in WebSocket in Node.js
Storing custom objects in WebSocket in Node.js

Time:10-29

I'm using a WebSocketServer. When a new client connects I need to store data about that client as a custom object for each client and I want to be able to store it in the WebSocket so when the server receives a new message from that client I can quickly access my custom object from the WebSocket itself. Is there any way to do this or do I just have to create a map for all my objects and lookup the object from the WebSocket each time based on it's ID? Thanks

CodePudding user response:

The Map idea will work to lookup each connection's data, but there's also no reason why you can't just add your own custom property to the webSocket object.

wss.on('connection', socket => {
     socket.userInfo = {someProperty: 'someValue'};

     socket.on('message', data => {
         console.log(socket.userInfo);
     });
});

Then, the .userInfo property will be available any time you get a message on that socket object.

Keep in mind that this info is temporal and only good for the lifetime of the socket object. So, if the client disconnects and reconnects (such as when changing web pages), that will generate a new socket object that will not have the previous .userInfo property on it. So, if that information needs to persist longer than the lifetime of one connection, you will have to store it elsewhere and index it by some persistent user property, not just the socket object.

  • Related