WebSocket Subprotocols

WebSockets are a handy transport mechanism. They're based on TCP and thus are provide ordered and reliable messaging, build on top of HTTP and thus inherit many nice properties like how they leverage URLs or are easy to route, and are widely supported by browsers.

There are a couple of RFCs that describe WebSockets:

There is also of course the browser API. Although I for one usually prefer to browser MDN.

So, what about subprotocols?

Now, there's a feature that's often glossed over, which is the use of subprotocols. The RFC says:

The |Sec-WebSocket-Protocol| request-header field can be to indicate what subprotocols (application-level protocols over the WebSocket Protocol) are acceptable to the client. The server selects one or none of the acceptable protocols and echoes that value in its handshake to indicate that it has selected that protocol.

So, the client might send Sec-WebSocket-Protocol: chat, superchat, and the server might respond with Sec-WebSocket-Protocol: chat.

If you care to see what some registered subprotocols exist, take a look at the IANA Registry. Of course you are free to mint your own if you're not going after interoperability.

Interestingly, the registry includes the note "This table also includes subprotocol identifiers specified for usage within a WebRTC data channel. but that's a story for another day.

Some servers ignore the protocol headers, others require it but don't do much, others might negotiate. But how do you specify what subprotocols you want from the client?

Your Library Here

Different libraries have approched this in a couple of ways.

So, there you have it. Four different libraries, four different ways of specifying subprotocols - constructor, headers, methods, collections. If you're using a different one, don't despair if you can't find the setting - it's probably hidden somewhere!

Happy subprotocol selections!

Tags:  cppdotnetjavascriptnet

Home