Does HTTP/2 make websockets obsolete?
Asked Answered
M

10

450

I'm learning about HTTP/2 protocol. It's a binary protocol with small message frames. It allows stream multiplexing over single TCP connection. Conceptually it seems very similar to WebSockets.

Are there plans to obsolete websockets and replace them with some kind of headerless HTTP/2 requests and server-initiated push messages? Or will WebSockets complement HTTP/2?

Maragretmarala answered 18/2, 2015 at 11:50 Comment(5)
I think that accepted answer is correct, websockets are still preferred solution for web applications to communicate with server bi-directionally including server-pushed messages. HTTP is used for more than just browsers and when both client and server can use low-level API, they don't need websockets. Still most people use HTTP for web applications and mostly concerned about JavaScript-exposed APIs. If moderators think that accepted answer should be different, I'm not opposed to that as this question apparently generates a lot of views and my opinion might be wrong.Maragretmarala
Lot of answers here considering HTTP/2 server push. This is being removed. evertpot.com/http-2-push-is-deadIndiscretion
@shadow0359 Not quite yet. The Chromium team has decided to keep it (for the time being at least). groups.google.com/a/chromium.org/g/blink-dev/c/K3rYLvmQUBY/m/…Inconsequent
Related: Why to use websocket and what is the advantage of using it?Alliber
^^ (and please vote to re-open this other question)Alliber
L
201

From what I understood HTTP/2 is not a replacement for websocket but aims to standardize SPDY protocol.

In HTTP/2, server-push is used behind the scene to improve resource loading by the client from the browser. As a developer, you don't really care about it during your development. However, with Websocket, the developer is allowed to use API which is able to consume and push message with an unique full-duplex connection.

These are not the same things, and they should complement each other.

Lepidote answered 18/2, 2015 at 12:18 Comment(10)
Thank you Guillaume for your answer. However I am wondering if you (or someone) could add some reference from the HTTP/2 specification. What I have read from blogs and so on - with HTTP/2 there is a true bidirectional communication?Jolandajolanta
Not sure the HTTP/2 spec is the right place to give details about the origins of HTTP/2 and how it differs from websocket. However, you can easily see that with HTTP/2 we are using a bidirectionnal communication: goo.gl/IJVxWS (page 6 and 13)Lepidote
HTTP/2 is indeed bidirectional but not symmetric, meaning that only the client can send a proper request and the server can send responses and request promises (push). This makes websockets different in the sense that both parties are more "equal" in terms of what they are allowed to send/receive.Septuor
There is an excellent podcast on IEEE's Software Engineering Radio about the origins of HTTP2. I think this is it: se-radio.net/2015/07/episode-232-mark-nottingham-on-http2Vaishnava
Yes. Over a single TCP connection request and response is multiplexed with full bi-directional communication and is part of the solution to the Head-Of-Line Blocking issue. Here is a nice overview of this and related issues readlearncode.com/http2-in-a-nutshellSidell
It is my understanding that the only benefit to continuing to use WS along with HTTP/2 is that with WS the request and response constitute less data/overhead. With the exception of maybe cookies, I think HTTP/2 always sends headers with every individual request (ie stream id) like Accept: and Content-Length and If-Modified-Since, etc. and a lot of these the browser has control over, not the page app code. So yes, the complement is partially true for non-webby uses, but chances are your web-app won't get to a level where optimizing out the headers would be a make-or-break situation.Sarraute
similar answer with full rationale can be found in this InfoQ article here: infoq.com/articles/websocket-and-http2-coexistHaunted
The infoQ paper is wrong, it says that only browsers can consume server push, while Jetty provides an HTTP2Client with server push support: #30010516Spiro
It is already arrived in chrome. chromestatus.com/feature/6251293127475200Rutter
This answer focuses a lot on server-push, but I think that's largely dead now that chrome has dropped it and many browsers never added it: developer.chrome.com/blog/removing-push However, it is partly replaced by HTTP 103 and maybe SSE for some use-cases.Journeywork
E
356

After just getting finished reading RFC 7540, HTTP/2 does obsolete websockets for all use cases except for pushing binary data from the server to a JS webclient. HTTP/2 fully supports binary bidi (bidirectional) streaming (read on), but browser JS doesn't have an API for consuming binary data frames and AFAIK such an API is not planned.

For every other application of bidi streaming, HTTP/2 is as good or better than websockets, because (1) the spec does more work for you, and (2) in many cases it allows fewer TCP connections to be opened to an origin.

PUSH_PROMISE (colloquially known as server push) is not the issue here. That's just a performance optimization.

The main use case for Websockets in a browser is to enable bidirectional streaming of data. So, I think the OP's question becomes whether HTTP/2 does a better job of enabling bidirectional streaming in the browser, and I think that yes, it does.

First of all, it is bi-di. Just read the introduction to the streams section:

A "stream" is an independent, bidirectional sequence of frames exchanged between the client and server within an HTTP/2 connection. Streams have several important characteristics:

A single HTTP/2 connection can contain multiple concurrently open streams, with either endpoint interleaving frames from multiple streams.

Streams can be established and used unilaterally or shared by either the client or server.

Streams can be closed by either endpoint.

Articles like this (linked in another answer) are wrong about this aspect of HTTP/2. They say it's not bidi. Look, there is one thing that can't happen with HTTP/2: After the connection is opened, the server can't initiate a regular stream, only a push stream. But once the client opens a stream by sending a request, both sides can send DATA frames across a persistent socket at any time - full bidi.

That's not much different from websockets: the client has to initiate a websocket upgrade request before the server can send data across, too.

The biggest difference is that, unlike websockets, HTTP/2 defines its own multiplexing semantics: how streams get identifiers and how frames carry the id of the stream they're on. HTTP/2 also defines flow control semantics for prioritizing streams. This is important in most real-world applications of bidi.

(That wrong article also says that the Websocket standard has multiplexing. No, it doesn't. It's not really hard to find that out, just open the Websocket RFC 6455 and press ⌘-F, and type "multiplex". After you read

The protocol is intended to be extensible; future versions will likely introduce additional concepts such as multiplexing.

You will find that there is 2013 draft extension for Websocket multiplexing. But I don't know which browsers, if any, support that. I wouldn't try to build my SPA webapp on the back of that extension, especially with HTTP/2 coming, the support may never arrive).

Multiplexing is exactly the kind of thing that you normally have to do yourself whenever you open up a websocket for bidi, say, to power a reactively updating single page app. I'm glad it's in the HTTP/2 spec, taken care of once and for all.

If you want to know what HTTP/2 can do, just look at gRPC. gRPC is implemented across HTTP/2. Look specifically at the half and full duplex streaming options that gRPC offers. (Note that gRPC doesn't currently work in browsers, but that is actually because browsers (1) don't expose the HTTP/2 frame to the client javascript, and (2) don't generally support Trailers, which are used in the gRPC spec.)

Where might websockets still have a place? The big one is server->browser pushed binary data. HTTP/2 does allow server->browser pushed binary data, but it isn't exposed in browser JS. For applications like pushing audio and video frames, this is a reason to use websockets.

Edit: Jan 17 2020

Over time this answer has gradually risen up to the top (which is good, because this answer is more-or-less correct). However there are still occasional comments saying that it is not correct for various reasons, usually related to some confusion about PUSH_PROMISE or how to actually consume message-oriented server -> client push in a single page app.

If you need to build a real-time chat app, let's say, where you need to broadcast new chat messages to all the clients in the chat room that have open connections, you can (and probably should) do this without websockets.

You would use Server-Sent Events to push messages down and the Fetch api to send requests up. Server-Sent Events (SSE) is a little-known but well supported API that exposes a message-oriented server-to-client stream. Although it doesn't look like it to the client JavaScript, under the hood your browser (if it supports HTTP/2) will reuse a single TCP connection to multiplex all of those messages. There is no efficiency loss and in fact it's a gain over websockets because all the other requests on your page are also sharing that same TCP connection. Need multiple streams? Open multiple EventSources! They'll be automatically multiplexed for you.

Besides being more resource efficient and having less initial latency than a websocket handshake, Server-Sent Events have the nice property that they automatically fall back and work over HTTP/1.1. But when you have an HTTP/2 connection they work incredibly well.

Here's a good article with a real-world example of accomplishing the reactively-updating SPA.

Espouse answered 26/2, 2017 at 6:14 Comment(22)
This answer partially disagrees with the other ones, including the accepted one, and it's also the best answer because it's based on direct sources.Skipton
I do fully agree with this answer and the comment. HTTP/2 is streambased bidirectional.Jolandajolanta
I did go to RFC 6455 and find the word multiplexing. Here it is: > The protocol is intended to be extensible; future versions will likely introduce additional concepts such as multiplexing.Thunderstorm
Actually correct answer, the guy bothered to check the sources and real world application (grpc)Ivo
HTTP/2 does support bidirectional connections but it doesn't mean that HTTP/2 obsoletes WebSockets. Bidirectional connections can only be established by using details of the protocol that are not intended to be exposed in Web-APIs. If HTTP/2 obsoltes WebSockets, then HTTP/1.1 might also obsolte WebSockets. HTTP/1.1 already supports bidirectional connections using the Upgrade header. This header was later used to implement WebSockets over HTTP/1.1. Now, we also seem to get WebSockets using the bidirectional capabilities of HTTP/2.Tumefaction
What's a concrete use-case for web sockets that HTTP/2 doesn't cover?Espouse
@Espouse Bidirectional streaming of binary data from an JS app to an HTTP server. HTTP2 Server push to a JS app is only available with Server-Sent Events (SSE) and SSE cannot handle binary data.Braxton
I think masonk needs to take a look at Jeet Prakash's answer and update his knowledge. HTTP/2 does not replace Websockets when the server application needs to push to the client when the server initiates is (pub/sub). For this reason masonks answer is misleading.Stores
In websockets, the server can't start pushing arbitrary bytes until the client initiates a websocket upgrade request, but then it can push at any time. In HTTP/2, the server can't start pushing bytes until the client initiates a data connection, but then it can push bytes at any time. What's the functional difference? As I've pointed out, the PUSH_PROMISE capability is a red herring. It is not the reason why HTTP/2 is a replacement for web sockets. It is just a minor performance optimization off to the side. It has nothing to do with the heart of HTTP/2, which is the bidi streaming.Espouse
This answer is simply wrong. It confuses so many aspects that it's easily confusing. However, the crux of the matter is that the "bidi" HTTP/2 streams are request-response driven (and limited in number), whereas the WebSockets protocol is a true message based bidi protocol (it isn't request-response based, except for the handshake phase). This is a huge difference that can't be bridged just by misreading the specification (as @Espouse unintentionally appears to have done).Solanaceous
@Myst: Well, one thing's certain: one of us has misread the spec ;)Espouse
@Espouse yes... ;) ... I did implemented an HTTP/2 server a few years back, so I might be biased in thinking I’m right :-pSolanaceous
I'm not understand your objection, Myst, (but OTOH, I don't want to give wrong information). Could you contact me and explain more fully? mason at masonkramer.netEspouse
Excellent answer, exactly what I needed to hear to confirm my thoughts in my current project thinking about using http2Theine
Hi @Solanaceous and masonk from everything said so far, asides the binary data stream websocket is said to have, which by the way there might be support, if the support doesn't already exist for http/2, most of what everyone has been saying is the data going to browser cache or some browser storage, which at the time there are cache api exposed by the browser, there is service workers which apparently can access indexeddb, a client indexeddb polling is quite good for looking realtime for text based streams. Also SSE & fetch to the rescue on text based streams too. Correct me if misconceived/errMyrtlemyrvyn
psa: I understand Cache so far does not allow direct access to get what has been cached only browser can get it, we can only put into it, but indexeddb allows both browser and us to access the indexeddb, and a polling to indexeddb is network cost freeMyrtlemyrvyn
@Myrtlemyrvyn : I would add that the idea that HTTP/2 Push Promise will actually reach the browser is somewhat misguided. In fact, Google suggested that the feature be deprecated. Push Promise was designed to push CSS and Javascript along with the original page. However, implementations are often abused or misused. Push Promise was never designed for push notifications and the resource pushed might never be processed by the browser (and hence, never effect the local cache).Solanaceous
I see, thanks @Solanaceous , lol, just when I was considering making use of the feature in future developments, as my standard way, it is about to get deprecated. Oh well, I will still give it a try for pet projects and experiments, while making sure it is used right and I can atleast "master" it, incase it stays in the light. Also, I have noticed people have used workarounds, as I have used similar concepts for preloading JS code and normal data in SPAs, the issue is probably lack of educating developers with proper guidance.Myrtlemyrvyn
It’s helpful to ignore PUSH_PROMISE (server push). It’s a distraction from understanding HTTP/2 and is rarely used and even more rarely used correctly. It really doesn’t matter and it has no bearing on the question of websockets vs http/2.Espouse
For the folks who thinks http2 replaces websocket. Could you give me an code example , with raw http2 client, to have a simple server/client setup doing what one typically do with websocket? ie, client initiate connection. server and client starts ping-pong messages to each other within that connection.Trichiasis
http2 closes connection eventually after client or server idle time (30s), where websockets are not. So I dont think http2 is making websockets obsoleteTumble
@Tumble your assertion about the HTTP/2 spec (that "http2 closes connection eventually after client or server idle time (30s)" is false. datatracker.ietf.org/doc/html/… section 9.1 HTTP/2 connections are persistent. For best performance, it is expected that clients will not close connections until it is determined that no further communication with a server is necessary. Furthermore, even if your premise had been true, it wouldn't have been enough of a reason to use websockets. You could set up keepalive heartbeats.Espouse
L
201

From what I understood HTTP/2 is not a replacement for websocket but aims to standardize SPDY protocol.

In HTTP/2, server-push is used behind the scene to improve resource loading by the client from the browser. As a developer, you don't really care about it during your development. However, with Websocket, the developer is allowed to use API which is able to consume and push message with an unique full-duplex connection.

These are not the same things, and they should complement each other.

Lepidote answered 18/2, 2015 at 12:18 Comment(10)
Thank you Guillaume for your answer. However I am wondering if you (or someone) could add some reference from the HTTP/2 specification. What I have read from blogs and so on - with HTTP/2 there is a true bidirectional communication?Jolandajolanta
Not sure the HTTP/2 spec is the right place to give details about the origins of HTTP/2 and how it differs from websocket. However, you can easily see that with HTTP/2 we are using a bidirectionnal communication: goo.gl/IJVxWS (page 6 and 13)Lepidote
HTTP/2 is indeed bidirectional but not symmetric, meaning that only the client can send a proper request and the server can send responses and request promises (push). This makes websockets different in the sense that both parties are more "equal" in terms of what they are allowed to send/receive.Septuor
There is an excellent podcast on IEEE's Software Engineering Radio about the origins of HTTP2. I think this is it: se-radio.net/2015/07/episode-232-mark-nottingham-on-http2Vaishnava
Yes. Over a single TCP connection request and response is multiplexed with full bi-directional communication and is part of the solution to the Head-Of-Line Blocking issue. Here is a nice overview of this and related issues readlearncode.com/http2-in-a-nutshellSidell
It is my understanding that the only benefit to continuing to use WS along with HTTP/2 is that with WS the request and response constitute less data/overhead. With the exception of maybe cookies, I think HTTP/2 always sends headers with every individual request (ie stream id) like Accept: and Content-Length and If-Modified-Since, etc. and a lot of these the browser has control over, not the page app code. So yes, the complement is partially true for non-webby uses, but chances are your web-app won't get to a level where optimizing out the headers would be a make-or-break situation.Sarraute
similar answer with full rationale can be found in this InfoQ article here: infoq.com/articles/websocket-and-http2-coexistHaunted
The infoQ paper is wrong, it says that only browsers can consume server push, while Jetty provides an HTTP2Client with server push support: #30010516Spiro
It is already arrived in chrome. chromestatus.com/feature/6251293127475200Rutter
This answer focuses a lot on server-push, but I think that's largely dead now that chrome has dropped it and many browsers never added it: developer.chrome.com/blog/removing-push However, it is partly replaced by HTTP 103 and maybe SSE for some use-cases.Journeywork
S
100

I say Nay (Websockets aren't obsolete).

The first and most often ignored issue is that HTTP/2 push isn't enforceable and might be ignored by proxies, routers, other intermediaries or even the browser.

i.e. (from the HTTP2 draft):

An intermediary can receive pushes from the server and choose not to forward them on to the client. In other words, how to make use of the pushed information is up to that intermediary. Equally, the intermediary might choose to make additional pushes to the client, without any action taken by the server.

Hence, HTTP/2 Push can't replace WebSockets.

Also, HTTP/2 connections do close after a while.

It's true that the standard states that:

HTTP/2 connections are persistent. For best performance, it is expected that clients will not close connections until it is determined that no further communication with a server is necessary (for example, when a user navigates away from a particular web page) or until the server closes the connection.

But...

Servers are encouraged to maintain open connections for as long as possible but are permitted to terminate idle connections if necessary. When either endpoint chooses to close the transport-layer TCP connection, the terminating endpoint SHOULD first send a GOAWAY (Section 6.8) frame so that both endpoints can reliably determine whether previously sent frames have been processed and gracefully complete or terminate any necessary remaining tasks.

Even if the same connection allows for pushing content while it is open and even if HTTP/2 resolves some of the performance issues introduced by HTTP/1.1's 'keep-alive'... HTTP/2 connections aren't kept open indefinitely.

Nor can a webpage re-initiate an HTTP/2 connection once closed (unless we're back to long-pulling, that is).

EDIT (2017, two years later)

Implementations of HTTP/2 show that multiple browser tabs/windows share a single HTTP/2 connection, meaning that push will never know which tab / window it belongs to, eliminating the use of push as a replacement for Websockets.

EDIT (2020)

I'm not sure why people started downvoting the answer. If anything, the years since the answer was initially posted proved that HTTP/2 can't replace WebSockets and wasn't designed to do so.

Granted, HTTP/2 might be used to tunnel WebSocket connections, but these tunneled connections will still require the WebSocket protocol and they will effect the way the HTTP/2 container behaves.

Solanaceous answered 27/8, 2015 at 19:29 Comment(6)
WS sockets won't stay open forever either. The differences is streams; HTTP/2 provides you with multiple stream flows which means flow control on the server is very different and often lockless. WS (as a protocol) has to have unregulated inbound processing. Flow control is implemented higher up the stack. For security and server integrity, HTTP/2 is much better than WS.Diesis
@bond, I agree that HTTP/2 has many advantages as a transport layer (sharing a single connection across many browser tabs is just one example). However, it isn't designed as a communication layer. It is a functional question. Both protocols answer different needs. i.e. implementing an ssh terminal on the browser is a breeze when using Websockets. It would be a total headache on HTTP/2, especially if more then one tab is open. Also, what if the browser (or one of the HTTP/2 proxies) closed the connection? Can the client just assume no new data is available? we're back to polling.Solanaceous
The browser can just as easily close your WS connection. That is life with any kind of networking. To be honest, the multiplexing in HTTP/2 is overkill. The protocol really didn't need it. With opening multiple streams you start running into problems with the TCP buffers limiting throughput. I agree with you that WS is better at what it does than HTTP/2. Fundamentally, WS is something that needs a lot of higher level controls to prevent users from doing bad things.Diesis
To quote Uncle Ben (Spider-Man): "Remember, with great power comes great responsibility". Yes, @bond, you're very right. Websockets, being a very "raw" protocol, requires a more responsible server design. And yes, WS can be closed as easily as HTTP/2, but WS supports the onclose callback, so no polling is necessary. As for the multiplexing, I think it was a necessity rather then a choice. keep-alive failed and the only way to avoid the "first-in-line" performance hit was to risk multiplexing. Time will tell :)Solanaceous
From a server design point of view outbound multiplexing is a complicated and expensive problem. It requires the IO mechanics to poll internally which is expensive as hell. Unless you are streaming large documents the multiplexing won't even function because the request will probably have responded and buffered fully internally before the second even becomes available and the multiplexing fails to run. RTMP has outbound multiplexing but only Adobe's server does it. It is amazing how close HTTP/2 is to RTMP.Diesis
For people commenting HTTP/2's push was basically targeted for the resources of an HTML page, or other such related resources, being pushed before they're requested. People are just thinking about web-pages, there are other cases like online games. If WebSockets were obsolete then this wouldn't exist tools.ietf.org/html/rfc8441Ermeena
D
51

The answer is no. The goal between the two are very different. There is even an RFC for WebSocket over HTTP/2 which allows you to make multiple WebSocket connections over a single HTTP/2 TCP pipe.

WS over HTTP/2 will be a resource conservation play by decreasing the time to open new connections and allowing for more communication channels without the added expense of more sockets, soft IRQs, and buffers.

https://datatracker.ietf.org/doc/html/draft-hirano-httpbis-websocket-over-http2-01

Diesis answered 21/1, 2016 at 0:22 Comment(11)
That's amazing! Is there any public example of a Javascript client which has implemented this? I can't find any examples. What would I need to do? Is this a good resource? undertow.io/blog/2015/04/27/An-in-depth-overview-of-HTTP2.htmlPsalms
Does anyone know a source of the above claims about 1) finding the length of the header, 2) lower casing the field names?Entomology
@PimHeijden detecting the header length in HTTP/1.x requires looping through all the bytes looking for the 4 byte end marker. That is very expensive. The case-insentivieity of the field names also means that any field matching must be done for both the upper and lower case version of the characters. This requires knowledge of the entire charset to upper and lower case for the checks. In 2.x you can assume they're lower case.Diesis
@Psalms You can't control any of this from Javascript. The browser does everything for you.Diesis
@bond I'm currently using HTTP/2 with Nginx, and proxy_pass to send websocket connections to a socket server, but when I have a single user open multiple tabs in the website, the socket server treats it as multiple connections. I would assume that if HTTP/2 is multiplexing connections over one TCP pipe, the server would treat it as one connection. Is this wrong? Is there any way to verify that the server isn't making extra unnecessary connections?Psalms
@Psalms WebSockets work over HTTP/1.1 using the upgrade command and that isn't compatible with HTTP/2 yet. see blog.sessionstack.com/…Diesis
@Psalms Sorry, I was logged into the wrong account. That was confusing.Diesis
@bond Can you support those claims made in the previous edit? Although relation with the main question is a bit unclear, those performance gains in relation to 1) the length and 2) the lowercasing of the headers are super interesting. It is hard to find good but simple reads about it.Entomology
@PimHeijden - I don't have a thesis paper about it or anything. I've written three HTTP servers - all with varying levels of complexities and purposes in order to gain the most performance for a specific use-case. Iterating over all of the bytes in the byte stream looking for a four byte marker is expensive and you have to get real creative with it unless you're writing the server in C. If you're trying to consume 1+ million HTTP/1.1 messages per second, looping eats a lot of cycles.Diesis
@bond So the answer is no? Would be cool to read about your results somewhere.Entomology
@PimHeijden I'd be happy to discuss this with you further but this really isn't a great place.Diesis
L
32

Well, to quote from this InfoQ article:

Well, the answer is clearly no, for a simple reason: As we have seen above, HTTP/2 introduces Server Push which enables the server to proactively send resources to the client cache. It does not, however, allow for pushing data down to the client application itself. Server pushes are only processed by the browser and do not pop up to the application code, meaning there is no API for the application to get notifications for those events.

And so HTTP2 push is really something between your browser and server, while Websockets really expose the APIs that can be used by both client (javascript, if its running on browser) and application code (running on server) for transferring real time data.

Lynlyncean answered 4/11, 2017 at 7:4 Comment(1)
HTTP2 Push is not intended to make websockets obsolete. To stream utf-8 text data from server to client, you should use SSE (server side events) in http2. Other direction can make use of traditional POST or GET requests,because http2 is way more optimized for this kind of traffic. It use single TCP connection in all of given traffic.Baboon
F
10

As of today, no.

HTTP/2, compared to HTTP, allows you to maintain a connection with a server. From there, you can have multiple streams of data at the same time. The intent is that you can push multiple things at the same time even without the client requesting it. For example, when a browser asks for a index.html, the server might want to also push index.css and index.js. The browser didn't ask for it, but the server might provide it without being asked because it can assume you're going to want in a few seconds.

This is faster than the HTTP/1 alternative of getting index.html, parsing it, discovering it needs index.js and index.css and then building 2 other requests for those files. HTTP/2 lets the server push data the client hasn't even asked for.

In that context, it's similar to WebSocket, but not really by design. WebSocket is supposed to allow a bi-directional communication similar to a TCP connection, or a serial connection. It's a socket where both communicate with each other. Also, the major difference is that you can send any arbitrary data packets in raw bytes, not encapsulated in HTTP protocol. The concepts of headers, paths, query strings only happen during the handshake, but WebSocket opens up a data stream.

The other difference is you get a lot more fine-tuned access to WebSocket in Javascript, whereas with HTTP, it's handled by the browser. All you get with HTTP is whatever you can fit in XHR/fetch(). That also means the browser will get to intercept and modify HTTP headers without you being able to control it (eg: Origin, Cookies, etc). Also, what HTTP/2 is able to push is sent to the browser. That means JS doesn't always (if ever) know things are being pushed. Again, it makes sense for index.css and index.js because the browser will cache it, but not so much for data packets.

It's really all in the name. HTTP stands for HyperText Transfer Protocol. We're geared around the concept of transferring assets. WebSocket is about building a socket connection where binary data gets passed around bidirectionally.


The one we're not really discussing is SSE (Server-Sent Events). Pushing data to the application (JS) isn't HTTP/2's intent, but it is for SSE. SSE gets really strengthened with HTTP/2. But it's a not a real replacement for WebSockets when what's important is the data itself, not the variable endpoints being reached. For each endpoint in with WebSocket a new data stream is created, but with SSE it's shared between the already existing HTTP/2 session.


Summarized here are the objectives for each:

  • HTTP - Respond to a request with one asset
  • HTTP/2 - Respond to a request with multiple assets
  • SSE - Respond with a unidirectional text (UTF-8) event stream
  • WebSocket - Create a bidirectional binary data stream
Fallal answered 20/5, 2020 at 14:42 Comment(3)
Does SSE on HTTP/2 suffer from the same limitation as on HTTP1.1: a limited number of active connections per domain? (the limitation is in Web browsers, around 5 simultaneous connections to the same server hostname, so if you have 3 SSE connections from the client to your my-server.com, you are left with only 2 connections for regular HTTP requests to the same my-server.com).Kamal
HTTP/2 ideally opens up a single session in one TCP connection, and then splits that session into multiple streams. The limits on number of sessions is generally seen to be 100 on browsers, though the can be decided by the server as well. To the operating system it's still one TCP connection.Fallal
@Paul-SebastianManole "When using HTTP/2, the maximum number of simultaneous HTTP streams [used to send SSE] is negotiated between the server and the client (defaults to 100)." developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/…Ebullience
G
6

No, WebSockets are not obsolete. However, HTTP/2 breaks websockets as defined for HTTP/1.1 (mostly by forbidding protocol updates using the Upgrade header). Which is why this rfc:

https://datatracker.ietf.org/doc/html/rfc8441

defines a websocket bootstrapping procedure for HTTP/2.

Got answered 31/5, 2021 at 1:22 Comment(0)
R
5

Message exchange and simple streaming(not audio, video streaming) can be done via both Http/2 multiplexing and WebSockets. So there is some overlap, but WebSockets have well established protocol, a lot of frameworks/APIs and less headers overhead. Here is nice article about the topic.

Rommel answered 12/1, 2017 at 18:48 Comment(0)
V
4

No HTTP/2 does not make websockets obsolete, but SSE over HTTP/2 offers a viable alternative. The minor caveat is that SSE does not support unsolicited events from server to client (and neither does HTTP/2): i.e. the client has to explicitly subscribe by creating an EventSource instance specifying the event source endpoint. So you may have to slightly reorganise how the client arranges for events to be delivered - I can't think of a scenario where this is actually a technical barrier.

SSE works with HTTP/1.1. But HTTP/2 makes using SSE generally viable and competitive with websockets in terms of efficiency, instead of practically unusable in the case of HTTP/1.1. Firstly, HTTP/2 multiplexes many event source connections (or rather "streams" in HTTP/2 terms) onto a single TCP connection where as in HTTP/1.1 you'd need one connection for each. According to the HTTP/2 spec, millions of streams can be created per connection by default with the recommended (configurable) minimum being 100, where as browsers maybe severly limited in the number of TCP connections they can make. Second reason is efficiency: many streams in HTTP/2 is requires much less overhead than the many connections required in HTTP/1.1.

One final thing is, if you want to replace websockets with SSE your forgoing some of the tools / middlewares built on top of websockets. In particular I'm thinking of socket.io (which is how a lot of people actually use websockets), but I'm sure there is a ton more.

Vicarious answered 3/10, 2022 at 5:53 Comment(0)
C
1

For the time being April 2020, HTTP/2 is not making WebSockets obsolete. The greatest advantage of WebSockets over HTTP2 is that

HTTP/2 works only on Browser Level not Application Level

Means that HTTP/2 does not offer any JS API like WebSockets to allow communication and transfer some kind of JSON or other data to server directly from Application (e.g. Website). So, as far as I believe, HTTP/2 will only make WebSockets obsolete if it starts offering API like WebSockets to talk to server. Till that it is just updated and faster version of HTTP 1.1.

Conjunctivitis answered 3/5, 2020 at 11:32 Comment(2)
What's fetch and EventSource if not an API to talk from the client to the server and from the server to the client?Deferred
@DavidMulder I said API Like WebSockets. Please consider the word LIKE. I did not say, it is not providing any API. Because WebSockets provide way more advance API functions on sending and receiving messages over full duplex on an Application Level. So, there is a huge differenceConjunctivitis

© 2022 - 2024 — McMap. All rights reserved.