0

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?

1 Answer 1

1

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);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes I have done that also.But how to check if header is set correctly?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.