Trying to find out if any attribute of the websocket server module can be used to extract a unique identifier for each unique client connecting to server .
So far tried following ,
however each of them yields unpredictable value ( ie works and doesnt work at times)
Ps : I am using websocket never without using express
You can add this info yourself every time a a new connection is established for example using node-uuid.
wss.on('connection', (ws) => {
ws.id = uuid.v4();
});
or you can use a query parameter if you want to identify a client when it connects.
var ws = new WebSocket('ws://example.com/?token=abc123');
@lpinca Can u explain it how to fetch that token parameter on the server side?
I tried we.token it's undefined?
@fvukovic
wss.on('connection', (ws, req) => {
const { query: { token } } = url.parse(req.url, true);
// ...
});
@lpinca
wss.on('connection', (ws, req) => {
const { query: { token } } = url.parse(req.url, true);
^
TypeError: Cannot read property 'url' of undefined
});
@sajadghawami use ws@>=3 or replace req with ws.upgradeReq.
@lpinca
Still getting same error:
wss.on('connection', (ws, req) => {
const { query: { token } } = url.parse(ws.upgradeReq.url, true);
^
TypeError: Cannot read property 'url' of undefined
});
Using "ws": "^4.0.0"
Reread my previous comment, upgrade or use upgradeReq, not both :). Since you are using ws@4 now the original snippet that uses req (https://github.com/websockets/ws/issues/859#issuecomment-362032885) is valid.
Ahh i see :) ... but using the one you posted before didn't work either with ws@4...
you mean this:
wss.on('connection', (ws, req) => {
const { query: { token } } = url.parse(req.url, true);
^
TypeError: Cannot read property 'url' of undefined
});
Yes that one, on ws@>=3, req can't be undefined so I think there is something wrong with your setup.
Run npm ls ws to see the installed ws version.
Use request header 'sec-websocket-key'
wss.on('connection', (ws, req) => {
var id = req.headers['sec-websocket-key'];
//do what ever you want...
});
wss.on('connection', function connection(ws,req) {
var url = req.url;
url = url.substring(1);
room = 1;
ws['room']= url;
// do any
});
@fvukovic
wss.on('connection', (ws, req) => { const { query: { token } } = url.parse(req.url, true); // ... });
url.parse is deprecated since Node v11. You can use the URL constructor instead.
Otherwise, you can simply do this if you only have one query parameter.
wss.on('connection', (ws, req) => {
ws.uuid = req.url.replace('/?uuid=', '')
});
Most helpful comment
You can add this info yourself every time a a new connection is established for example using
node-uuid.or you can use a query parameter if you want to identify a client when it connects.