Search code examples
tomcatwebsocketjava-websocket

Tomcat 9 http/2 Websockets


I was trying to use http/2 with my webapp. The Problem is that my websocket connection does not seem to work when using http/2.

I use an javascript file with var webSocket = new WebSocket('wss://xxx.de:8443/urlto/websocket');

and my Tomcat Connector in server.xml looks like this:

<Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
           maxThreads="150" SSLEnabled="true" >
    <UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" />
    <SSLHostConfig>
        <Certificate certificateKeyFile="/path/to/privkey.pem"
                     certificateFile="/path/to/cert.pem"
                     certificateChainFile="/path/to/chain.pem"
                     type="RSA" />
    </SSLHostConfig>
</Connector>

When starting the server like this, I get an Error saying connection closed before receiving a handshake response

If I do not include the <UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" /> part, the websocket connects without a problem.


Solution

  • WebSocket handshake is not defined for HTTP/2, thus if you want to use ws, you'll need to use HTTP/1.1.

    There was a RFC which was trying to define WS on HTTP/2, but it was never completed. It has been replaced with https://datatracker.ietf.org/doc/draft-mcmanus-httpbis-h2-websockets/, we'll have to see whether this will be the way.