Reputation: 126327
Is there a way for a WebSocket client to send additional information on the initial connection to the WebSocket server?
I'm asking because I want the client to send the user ID (string) to the server immediately. I don't want the client to send the user ID in the onopen callback. Why? Because it's faster and simpler.
If the WebSocket API won't let you do this, why not? If there's no good reason, how could I suggest they add this simple feature?
Upvotes: 17
Views: 20489
Reputation: 1983
Since v3 ws.upgradeReq
is deprecated and doesn't work anymore.
You can now use:
wss.on('connection', function(ws, req) {
console.log(req.url); # => '/4'
});
Source: https://github.com/websockets/ws#client-authentication
Upvotes: 3
Reputation: 126327
@dandavis is a genius. His comment on the question of sending the user ID in the query string of the first (url) argument of the WebSocket constructor works! And, I'm pretty sure it's only sent once by the client during the opening handshake (1.3) of the WebSocket protocol (RFC 6455).
It even worked to send it in the path, which I prefer for now since the WebSocket server I made is just for WebSockets. I'm using Node.js with ws. I'm connecting to the URL ws://localhost:5000/4
, where 4
is the user ID. To get the user ID, I do ws.upgradeReq.url
, like so:
wss.on('connection', function(ws) {
console.log(ws.upgradeReq.url); # => '/4'
});
Next, to make it secure, I'll pass the access token instead of the user ID.
You can pass the user ID (string) as the second (protocols) argument of the WebSocket constructor.
That should work, but it's not meant for what you want. It's definitely a hack. So, I don't recommend it. Also, the server will echo the user ID back to the client in its handshake. And, you don't need that. That would be extra data being sent over the wire that's of no use to you.
I'm not sure why the WebSocket API doesn't let you do what you want. Maybe it's more secure that way.
Upvotes: 16