Apoorva Sharma
Apoorva Sharma

Reputation: 13

Setting response headers in WebSocket server and verify in client using npm WebSocket server

I am creating a mock web server using ws library of node.js: https://www.npmjs.com/package/ws#api-docs

I need to set a protocol in Sec-WebSocket-Protocol header and send it to client, then verify the header on client side.

I tried below options:

wss.on('headers', function (headers) {
    console.log("on headers");
    headers.push(`sec-websocket-protocol: ${protocol}`);
})

Also this:

 var msg = {
        message: message,
        "sec-websocket-protocol": protocol
    };
ws.send(JSON.stringify(msg));

Nothing seems to work currently. Also on client side I am not sure on how to verify this header?

Upvotes: 0

Views: 2024

Answers (1)

gre_gor
gre_gor

Reputation: 6785

There is no need to mess with the headers yourself.

On the client side you list the protocols as the second arguemtn to the Websocket constructor.

const ws = new WebSocket(ws_url, ["protocol-1", "protocol-2", "protocol-3"]);

On the server side, you need to pass a handleProtocols function, to chose one of the available protocols.

var wss = new WebSocketServer({
    ...
    handleProtocols: (protocols, client) => {
        var protocol = /* choose one from protocols argument */;
        return protocol;
    },
    ...
});

Then on the client side you get the chosen protocol on the protocol property on your WebSocket object.

ws.onopen = function() {
    console.log("WS opened; protocol chosen:", this.protocol);
};
ws.onmessage = function(data) {
    if (this.protocol in protocol_handlers) {
        protocol_handlers[this.protocol](data.data);
    }
}

Upvotes: 1

Related Questions