Search code examples
httpwebsockethttp-response-codes

HTTP response code when requested websocket subprotocol isn't supported/recognized


When upgrading an HTTP connection to a websocket, one can provide one or more subprotocols in the optional HTTP header 'Sec-WebSocket-Protocol'.

If the server accepts any of the subprotocols it responds with HTTP response code 101 ("HTTP/1.1 101 Switching Protocols") and includes the HTTP header 'Sec-WebSocket-Protocol' indicating the selected subprotocol.

But how should the server correctly handle an unknown/unsupported subprotocol?

Should this be done 'within' the HTTP connection -- by use of some HTTP response code?

Or should the connection be upgraded to a websocket -- and immediately be closed by the server by sending a 'Close Frame' with some of the predefined websocket Status codes?

What does the RFC6455 say? I cannot come to a conclusion. How does existing server implementations handle it?

Regards /Per/


Solution

  • From a brief glimpse at RFC 6455, I believe the WebSocket Subprotocol is optional and negotiated. In section 4.2.2, under "Server Rquirements":

       /subprotocol/
          Either a single value representing the subprotocol the server
          is ready to use or null.  The value chosen MUST be derived
          from the client's handshake, specifically by selecting one of
          the values from the |Sec-WebSocket-Protocol| field that the
          server is willing to use for this connection (if any).  If the
          client's handshake did not contain such a header field or if
          the server does not agree to any of the client's requested
          subprotocols, the only acceptable value is null.  The absence
          of such a field is equivalent to the null value (meaning that
          if the server does not wish to agree to one of the suggested
          subprotocols, it MUST NOT send back a |Sec-WebSocket-Protocol|
          header field in its response).  The empty string is not the
          same as the null value for these purposes and is not a legal
          value for this field.  The ABNF for the value of this header
          field is (token), where the definitions of constructs and
          rules are as given in [RFC2616].
    

    The server should not send a subprotocol response header with a value other than 'null' if it did not agree to use the subprotocol with the client, and it is the client's responsibility to either continue or terminate the connection at that point.