Skip to content

WebSocket over HTTP2 #1458

Open
Open

Description

@rahbari

Now that node core has added websocket support over http2 nodejs/node#23284, It's nice to know when it will be added to WS?

Activity

  1. lpinca commented on Oct 15, 2018

    @lpinca
    Member

    See nodejs/node#23284 (comment). To answer your question, when someone interested in having the feature, will implement it and open a PR.

  2. ayZagen commented on Dec 25, 2018

    @ayZagen

    @lpinca We rely on ws and want to upgrade our servers to http2. It would be great to have http2 support on ws.
    Thanks

  3. lpinca commented on Dec 25, 2018

    @lpinca
    Member

    @ayZagen you are welcome to experiment with it. ws is built on top of the upgrade mechanism for HTTP/1.1 and works with a raw (net.Socket) TCP socket.

    The way WebSocket works over HTTP/2 is different, the HTTP/2 API is different so it's not trivial to add support for it. Here is a proof of concept: https://github.com/jasnell/http2ws/blob/master/http2ws.js. It might be easier to write a wrapper module with the eventual required additions in ws instead of adding support directly in ws.

    I am personally not interested in having HTTP/2 support because I think there is no real benefit in using an HTTP/2 stream instead of a raw TCP socket as the transport layer. I understand that in some cases it might be desirable to support HTTP/2 and WebSocket on the same server but I think that in many cases having a separate HTTP/1.1 server only for WebSocket is a good and viable option.

  4. FallingSnow commented on Jan 17, 2019

    @FallingSnow

    I'm using node's http2 framework with the allowHTTP1: true option. Then setting a ws server to listen on the http2 server just works.

    Although I would like to see ws support for HTTP2 so it feels less hacky.

  5. josephg commented on Jul 18, 2019

    @josephg

    @FallingSnow does that do websockets over http2 or is that just falling back to websockets over http1.1?

  6. josephg commented on Jul 18, 2019

    @josephg

    @lpinca the big advantage (architecturally) is taking advantage of multiplexing. Right now using websockets sort of requires you to throw away any http-like abstractions (and indeed we often just open a single ws connection to ws://example.com/ws or something) and do our own multiplexing.

    With ws over h2 it can start making sense again for applications / APIs to add per-URL websocket connections for specific change feeds / use cases. (Since all connections are multiplexed through the single h2 tcp socket anyway).

    The other advantage is faster connection times, since if the page is loaded over h2 then we don't need to do another tcp/TLS handshake to open a websocket.

  7. lpinca commented on Jul 18, 2019

    @lpinca
    Member

    WebSocket over HTTP2 has only one advantage that is as you said the use of a single TCP connection when the origin is the same. In all other cases there are only disadvantages especially on the server and with the Node.js HTTP2 implementation.

    Node.js HTTP2 adds a lot of overhead over a plain {net,tls}.Socket. There are streams wrapping other streams and the whole HTTP2 machinery. I did not run any benchmark but I'm pretty sure it would perform way worse in terms of both speed and especially memory usage.

    See also this discussion dotnet/aspnetcore#7801 and in particular this comment dotnet/aspnetcore#7801 (comment).

  8. FallingSnow commented on Jul 20, 2019

    @FallingSnow

    @josephg I believe the connection comes in as an HTTP1.1 request. There is no actual HTTP2 as far as I'm aware.

  9. damianobarbati commented on Aug 14, 2019

    @damianobarbati

    Check this out guys: https://nodejs.org/api/http2.html section "The Extended CONNECT Protocol"

  10. LongTengDao commented on Apr 8, 2020

    @LongTengDao
    Contributor

    By read all source code of ws (as server side), and find each place using socket, it seems that we only need do small change to support HTTP2:

    1. socket.write('HTTP/1.1 101 Switching Protocols\r\n...') change to socketOrStream.additionalHeaders ? socketOrStream.additionalHeaders({ ':status': 101, ... }) : socketOrStream.write('...');
    2. socket.setNoDelay(); change to socketOrStream.setNoDelay && socketOrStream.setNoDelay();;
    3. socket.on data end error close change to socketOrStream.on data end error close frameError aborted, and remember remove them at right time.

    Because net.Socket and (Server)Http2Stream are both stream.Duplex.

  11. masx200 commented on Apr 24, 2020

    @masx200

    Do any browsers support "websocket over http2" now?

  12. adelyte-chris commented on May 12, 2020

    @adelyte-chris

    HTTP/2 explicitly disallows WebSocket upgrades. See HTTP/2 Issue #386 for the current status of adding WebSockets semantics to HTTP/2.

  13. lpinca commented on May 13, 2020

    @lpinca
    Member

    @adelyte-chris RFC 8441 describes how to run the WebSocket protocol over a single stream of an HTTP/2 connection and this is already supported by Node.js.

    That said, I did not change my mind on this topic.

  14. adelyte-chris commented on May 15, 2020

    @adelyte-chris

    @lpinca My mistake, I saw the draft status of the RFC linked in the issue and didn't follow up to see if it had progressed.

    @masx200 Chromium has support for WebSockets over HTTP/2 behind a command line flag. I found a reference to Firefox support being in development but can't find a tracking issue for it.

  15. note8g2018 commented on Aug 14, 2020

    @note8g2018

    Do any browsers support "websocket over http2" now?

    No

  16. 2 remaining items

  17. luncheon commented on Apr 12, 2021

    @luncheon

    FYI: Websockets over HTTP/2 will be supported (enabled by default) in Chrome 91
    https://www.chromestatus.com/feature/6251293127475200

  18. szmarczak commented on Apr 12, 2021

    @szmarczak
  19. piranna commented on Jan 11, 2023

    @piranna

    Chrome 95 already supports that: https://chromestatus.com/feature/6251293127475200

  20. esinanturan commented on May 27, 2023

    @esinanturan

    Any plans for supporting it in this library ?

  21. CMCDragonkai commented on Aug 2, 2023

    @CMCDragonkai

    Here's a client example using http2-wrapper: https://github.com/szmarczak/http2-wrapper/blob/master/examples/ws/index.js

    @szmarczak it looks like you've managed to implement websockets over HTTP2 on both client side and server side using node's http2 module and this ws library. Is that production ready or are there other things that is still needed for full websocket over http2 support? (Like ping/pong... etc).

    Also why did you do this:

    ws.setSocket(stream, head, 100 * 1024 * 1024);
    

    What is the 100 * 1024 * 1024?

  22. brentmjohnson commented on Dec 14, 2023

    @brentmjohnson

    Use of ws server-side seems to work fine as-is with a native chromium WebSocket API client. HTTP/1 requests hit the "upgrade" event and HTTP/2 requests hit the "connect" event.

    Only thing I could imagine adding to ws might be a convenience handleConnect method to the server class, but that saves what - like 15 LOC?

    Node.js native http2 from "node:http2" for v20.10.0:

    const server = http2.createSecureServer(
      {
        key: syncfs.readFileSync("localhost-privkey.pem"),
        cert: syncfs.readFileSync("localhost-cert.pem"),
        allowHTTP1: true,
        settings: {
          enableConnectProtocol: true,
        }
      }
    );
    
    const wsServer = new WebSocket.Server({ noServer: true });
    
    const onConnectUpgrade = (ws, request) => {
      wsServer.emit("connection", ws, request);
    }
    
    server.on("upgrade", (request, socket, head) => {
      wsServer.handleUpgrade(request, socket, head, (ws) => onConnectUpgrade(ws, request));
    });
    
    server.on('connect', (request, response) => {
      if (request.headers[':protocol'] === 'websocket' &&
        request.headers[':method'] === 'CONNECT') {
        response.stream.respond({
          ':status': 200
        });
    
        const ws = new WebSocket(null);
        ws.setSocket(response.stream, Buffer.alloc(0), {
          maxPayload: 104857600,
          skipUTF8Validation: false,
        });
    
        onConnectUpgrade(ws, request);
      }
    });
    
    wsServer.on("connection", (socket, request) => {
      // do something with your new websocket!
    })
    

    Thanks for a great library!

  23. lpinca commented on Dec 15, 2023

    @lpinca
    Member

    @brentmjohnson your example only covers the server side and skipping wsServer.handleUpgrade() in the http2 case means ignoring

    • handshake validation.
    • hooks (verifyClient, 'headers' event, etc.).
    • permessage-deflate negotiation.
    • maybe other things I can't think of at the moment.
  24. ackava commented on Feb 14, 2024

    @ackava

    Chrome 121 onwards sends websocket over http/2, so WebSocket over HTTP2 is now kind of mandatory.

    @brentmjohnson your method works, however the socket is closed by Chrome browser after few seconds and it reconnects the server back again.

  25. brentmjohnson commented on Feb 15, 2024

    @brentmjohnson

    @ackava, i believe most browsers should respect the server's ALPN negotiation, but yeah if your server reports http2 and support for extended connect (re: RFC 8441) i would expect chrome to try websocket over http2.

    i haven't seen that disconnect issue on chrome 121.0.6167.185 or edge 123.0.2406.0. are you getting anything in the browser console, or perhaps have a proxy between the browser and the server?

  26. ackava commented on Feb 28, 2024

    @ackava

    @brentmjohnson Please Disregard my comment, the issue is with engine.io not handling connect event, your workaround does work correctly. I am currently using your work around to connect to socket.io over http1 and proxy the messages (yes overkilling CPU).

  27. masx200 commented on Mar 29, 2024

    @masx200

    any update?

  28. william-kerr commented on Apr 8, 2025

    @william-kerr

    See nodejs/node#23284 (comment). To answer your question, when someone interested in having the feature, will implement it and open a PR.

    I am thinking about forking ws, changing it all to TypeScript, ESM, adding a handleConnect method for http/2 and dropping utf-8-validate module support for old versions of Node.js.

    If I do, do you want me to submit a pull request for the total rewrite and let you publish a new major release 9.x.x, or would you prefer me to just make a separate npm package with a different name?

  29. luislobo commented on Apr 8, 2025

    @luislobo

    Probably not of any value but you got my +1 @william-kerr

  30. lpinca commented on Apr 9, 2025

    @lpinca
    Member

    @william-kerr if you do that, use a separate package with a different name.

  31. william-kerr commented on Apr 9, 2025

    @william-kerr

    @william-kerr if you do that, use a separate package with a different name.

    @lpinca, thanks for the quick reply, just wanted to reach out first for goodwill before doing something like that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions