Categories
JavaScript Answers

How to differentiate clients with webSocketServer in Node.js?

Spread the love

To differentiate clients with webSocketServer in Node.js, we canm use the sec-websocket-key header.

For instance, we write

wss.on("connection", (ws, req) => {
  ws.id = req.headers["sec-websocket-key"];

  //...
});

to listen to the connection event with on.

And we get the sec-websocket-key header with req.headers["sec-websocket-key"] in the event handler to get the client’s ID.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *