Search code examples
node.jshttpwebsockethttp2

HTTP2 - How to have WebSocket-like functionality (Keep-Alive, EventSource, etc.)


Wondering how to setup a persistent connection between client and server in Node.js.

The persistent connection should be able to send requests back and forth from both sides. It seems like it needs to have a mechanism for delineating each request, such as \r\n if requests are JSON, but not sure what best-practices are here if it's already been done before. Wondering how web-sockets handle this.

Mozilla says Keep-Alive shouldn't be used in production, so wondering if that still holds with HTTP2.

With EventSource you can receive server events, but wondering if there is a way to add client events to send to the server.

In the end, I would like to have a simple setup for two-way communication like WebSockets, but am not sure of best practices in HTTP2 and if it should just be done with WebSockets. I would prefer to try to do this without websockets.


Solution

  • With all due respect, I believe you're under the mistaken assumption that the HTTP/2 connection is page specific.

    In actuality, HTTP/2 connection are often browser wide connections. It's not possible for an HTTP/2 push to know which page/tab will use the data (possibly more than one).

    Also, see the discussion here that includes a myriad number of reasons as to why HTTP/2 couldn't (or shouldn't) be used as a Websocket alternative.

    On the other hand, if HTTP/2 is "promised" and Websockets are unavailable, than polling might be an option.

    Polling with HTTP/2 will be significantly more resource friendly than polling with HTTP/1.1, even though it would still be far more expensive than Websocket push (or poll) due to the extra header and authentication data (it will also decrease security, but that's probably something nobody really cares about all that much).

    P.S.

    Websockets over HTTP/2

    This is a non-issue unless HTTP/1.1 is retired (in fact, IMHO, this is intentional and good).

    It's true that HTTP/2 connections can't be "upgraded" (changed) to Websocket connections, nor can they tunnel Websocket data, but that means absolutely nothing.

    New Websocket connections use the existing HTTP/1.1 upgrade handshake and that's it.

    Any HTTP/2 server that supports Websockets will support the handshake.

    Keep-Alive

    Mozilla warns against the non-standard Keep-Alive header. However, the Connection: keep-alive standard for HTTP/1.1 (which is also the default for HTTP/1.1 clients) is definitely recommended.

    SSE (Server Sent Events)

    SSE pre-date Websockets and they didn't get much traction in the community, while Websockets were adopted with a vengeance.

    wondering if there is a way to add client events to send to the server

    Simple - send an HTTP request. The reply can be asynchronously received with SSE.

    I like Websockets better. As far as server-side goes, I find them easier to manage and code.