Ian Goldby
Ian Goldby

Reputation: 6195

Handling multiple subprotocols with System.Net.WebSockets

What is the correct way for a WebSockets server using HttpListener and System.Net.WebSockets to support multiple subprotocols?

I am using HttpListener to create an HttpListenerContext. On receiving a request with IsWebSocketRequest true the code calls AcceptWebSocketAsync with the subprotocol name as the parameter.

If the client request is for a different subprotocol then an exception is raised, which is to be expected.

There's no version of AcceptWebSocketAsync() that accepts a list of subprotocols and if I make two asynchronous calls to AcceptWebSocketAsync() with different subprotocols, only the latter is effective.

Edit 14 March

To clarify, I'm looking for support for the Sec-WebSocket-Protocol header such that the framework accepts a websockets upgrade based on finding a common subprotocol between those requested by the client and those supported by the server, and then tells the calling code in some way which (single) subprotocol has been agreed. (For example, in libwebsockets, you provide one callback per subprotocol.)

Upvotes: 2

Views: 1607

Answers (1)

Michał Komorowski
Michał Komorowski

Reputation: 6238

You have access to HttpListenerContext which has the Request property. It returns an instance of HttpListenerRequest which in turn has the Headers property. Headers returns a collection of name/value pairs. You should find there Sec-WebSocket-Protocol header.

Now you have the list of subprotocols requested by a client. You also know what subprotocols are known by a server so you easily perform matching.

However, to be honest I didn't try this approach and I'm aware that it is not a straightforward solution.

Upvotes: 2

Related Questions