Ws: Question: is ws.upgradeReq.headers['sec-websocket-key'] something we can rely on ?

Created on 25 Apr 2014  路  7Comments  路  Source: websockets/ws

I'm using

var clients = {};
wss.on('connection', function (ws) {
  var id = ws.upgradeReq.headers['sec-websocket-key'];
  clients[id] = {};

  ws.on('close', function () {
    delete clients[ws.upgradeReq.headers['sec-websocket-key']];
  });

  // ...
}

as client ID in a implem of WebSocket server, but I'm asking myself if this property is reliable ? and if you plan on renaming it ? Or maybe I should use a method to retrieve this key ?

Most helpful comment

It could be used as an ID because the spec requires a compliant client to generate a random key on each and every connection but it really depends on how the client generate that key.

In my opinion it's better to generate a proper uuid for each connection on the server in the connection listener.

All 7 comments

I'm using the same property to keep track of the client. I agree with maxleiko to have a better interface in getting this value to prevent us from versioning problems.

I would also like to add an interface of getting the cookie from the client.

var sessionId = Utils.getSession(ws.upgradeReq.headers.cookie);
var webSocketKey = ws.upgradeReq.headers['sec-websocket-key'];

Yeah, I agree, a public function to retrieve an unique client identifier would be very useful.

+1 for a unique client identifier.

Why not generate a random key ? Timestamp + random stuff

In ES6 to keep track of your own connection list you can just use a set:

var connections = new Set()

var wss = new WebSocketServer({server: server})
console.log("websocket server created")

wss.on("connection", function(ws) {
  connections.add(ws);

  ws.on("close", function() {
    connections.delete(ws);
  })
})

Also pretty sure WebSocketServer has its own clients property.

In any case, I have my own need for a unique client identifier so +1

+1 fer a unique _or_ an interface. Thx @maxleiko .. I was about an hour in of TNE time. Looks close to stable so not fussing.

var wss = new WebSocketServer({ port: process.env.PORT, verifyClient:function(info){
console.log(info.req.headers);
...
}});
==out===
{ connection: 'Upgrade',
upgrade: 'websocket',
host: 'localhost:8080',
'sec-websocket-version': '13',
'sec-websocket-key': 'MTMtMTQ2NDA1NzM4MTg3MQ==',
'sec-websocket-extensions': 'permessage-deflate; client_max_window_bits' }

It could be used as an ID because the spec requires a compliant client to generate a random key on each and every connection but it really depends on how the client generate that key.

In my opinion it's better to generate a proper uuid for each connection on the server in the connection listener.

Was this page helpful?
0 / 5 - 0 ratings