Home >Common Problem >SSE and WebSocket

SSE and WebSocket

百草
百草Original
2024-04-17 14:18:421213browse

In this article, we will compare Server Sent Events (SSE) and WebSocket, both reliable methods for delivering data. We will analyze them in eight aspects, including communication direction, underlying protocol, security, ease of use, performance, message structure, ease of use, and testing tools. A comparison of these aspects is summarized as follows: Category Server Sent Event (SSE) WebSocket Communication Direction Unidirectional Bidirectional Underlying Protocol HTTP WebSocket Protocol Security Same as HTTP Existing security vulnerabilities Ease of use Setup Simple setup Complex performance Fast message sending speed Affected by message processing and connection management Message structure Plain text Text or binary Ease of use Widely available WebSocket integration in demand Testing tools using Postman and collections using JMeter, Gadling, sse-perf, Testable or k6

SSE and WebSocket

In today's article, I want to take a closer look at Server Sent Events (SSE for short) and WebSockets. Both are proven and good data exchange methods.

SSE vs. WebSockets Image

I'll start with a brief characterization of these two tools - what they are and what they offer. I'll then compare them based on eight categories, which in my opinion are the most important for modern systems.

The categories are as follows:

  • Communication direction

  • Underlying protocol

  • Security

  • Simple

  • Performance

  • Message structure

  • Easy to Adopt

  • tooling

Contrary to my previous comparison comparing REST and gRPC, I will not declare any Points are awarded to the winner. Instead, in the summary paragraph, you'll find a kind of TL;DR table. This table contains the main differences between the two technologies in the areas mentioned above.

Why

Unlike REST, both SSE and WebSocket are more use case focused. In this particular case (or cases), the main focus of both concepts is to provide a "real-time" communication medium. Due to their specific focus, they are less popular than REST, which is a more general and one-size-fits-all tool.

Nonetheless, both SSE and WebSocket offer a range of interesting possibilities and are slightly newer than the classic REST approach to solving problems.

In my opinion, it's good to know about them and find some space for them in our toolbox, because one day they may come in handy to provide you with a simpler solution to quite Complex question - especially when you need "real-time" updates or when your application requires a more push-oriented approach.

In addition to comparing and describing them here, I Want to make them more popular?

What is WebSocket?

In short, WebSockets is a communication protocol that uses a single persistent TCP connection. Two-way communication is provided between the server and the client. Thanks to this feature, we do not have to constantly pull new data from the server. Instead, each message is exchanged "in real time" between the interested parties. Unicode text.

The protocol was standardized by the IETF in 2011 as RFC 6455. The WebSocket protocol is different from HTTP, but both are at layer 7 of the OSI model and rely on layer 4. TCP.

The protocol has its own unique set of prefixes that work similarly to the HTTP prefixes "http" and "https":

  • ws - indicates that the connection is not in use Protected by TLS

  • wss - Indicates that the connection is protected by TLS

Additionally, non-secure WebSocket connections should not be opened from secure sites (https) ( ws). Likewise, secure WebSocket connections (wss) should not be opened from non-secure sites (http)

WebSocket, on the other hand, is designed to work on HTTP ports 443 and 80, and supports proxies and intermediaries, etc. HTTP concept. Additionally, the WebSocket handshake uses the HTTP upgrade header to upgrade the protocol from HTTP to WebSocket.

The biggest disadvantage of WebSocket as a protocol is that it is not subject to the same origin policy, which may make things like CSRF attacks become easier.

What are server-sent events?

SSE is a technology that allows web servers to send updates to web pages. 5 part of the specification, similar to WebSocket, utilizing a single long-lived HTTP connection to send data "in real time"

At a conceptual level, it is a fairly old technology, with its theoretical background dating back to 2004. The first implementation of SSE was implemented in 2006

Most modern browsers support SSE - Microsoft Edge added SSE support in January 2020. It also takes full advantage of HTTP/2, which eliminates one of the biggest problems with SSE, effectively eliminated by HTTP/1.1.

By definition, server-sent events have two basic building blocks:

  • EventSource - an interface based on the WHATWG specification and implemented by browsers that allows clients (in In this case the browser) subscribes to the event.

  • Event Streaming - A protocol that describes a standard plain text format for server-sent events that an EventSource client must follow in order to understand and propagate them.

According to the specification, events can carry arbitrary text data, optional IDs, and are separated by newlines. They even have their own unique MIME type: text/event-stream.

Unfortunately, server-sent events as a technology are designed to only support text-based messages, although we can send them using custom formats event, but the final message must be a UTF-8 encoded string.

More importantly, SSE provides two very interesting features:

  • Auto-reconnect - If the client unexpectedly disconnects, EventSource will periodically try to reconnect connect.

  • Automatic Stream Resume - The EventSource automatically remembers the last received message ID and automatically sends the Last-Event-ID header when trying to reconnect.

Comparison

Communication Direction

The biggest difference between the two may be their communication style.

  • SSE provides only one-way communication - events can only be sent from the server to the client.

  • WebSockets provide complete two-way communication, enabling interested parties to exchange information and react to any events on both sides.

I would say that both approaches have their pros and cons, and each has a dedicated set of use cases.

On the one hand, if you only need to push a continuously updated stream to the client, then SSE will be a more suitable choice. On the other hand, if you need to react to one of these events in any way, then WebSocket may be more advantageous.

In theory (and practice), everything that can be done with SSE can also be done with WebSocket, but we are getting into areas like support, simplicity of the solution, or security.

I will describe all of these areas and more in the paragraphs below. Additionally, using WebSocket is likely to be a severe overkill in all cases, while an SSE-based solution may be easier to implement.

Underlying Protocol

This is another huge difference between the two technologies.

  • SSE relies entirely on HTTP and supports HTTP/1.1 and HTTP/2.

  • In contrast, WebSocket uses its own custom protocol - surprisingly - the WebSocket protocol.

As far as SSE is concerned, leveraging HTTP/2 solves one of the main problems of SSE - the maximum parallel connection limit. HTTP/1.1 limits the number of parallel connections according to its specification.

This behavior can cause a problem called head-of-line blocking. HTTP/2 solves this problem by introducing multiplexing, thus solving HOL blocking at the application layer. However, head-of-line blocking can still occur at the TCP level.

Regarding the WebSocket protocol, I have mentioned it in detail in the above lines. Here I just reiterate the most important points. The protocol differs slightly from classic HTTP, although the HTTP Upgrade header is used to initialize a WebSocket connection and effectively change the communication protocol.

Nonetheless, it also uses the TCP protocol as its base and is fully compatible with HTTP. The biggest drawback of the WebSocket protocol is its security.

Easy

In general, setting up an SSE-based integration is simpler than its WebSocket integration. The most important reason behind this is the nature of communication utilized by a particular technology.

The one-way approach of SSE and its push model makes it easier on a conceptual level. Combine this with automatic reconnect and stream continuity support out of the box, and we have significantly less to deal with.

With all these features, SSE can also be considered as a way to reduce coupling between client and server. The client only needs to know the endpoint that generated the event.

However, in this case, the client can only receive messages, so if we want to send any kind of information back to the server, we need another communication medium, which may make things very complicated.

As far as WebSocket is concerned, the situation is a bit complicated. First, we need to handle the connection upgrade from HTTP protocol to WebSockets protocol. Even though this is the simplest thing to do, it's another thing we need to remember.

The second problem comes from the two-way nature of WebSocket. We have to manage the state of a specific connection and handle all possible exceptions that may occur while processing messages. For example, what if processing one of the messages throws an exception on the server side?

The next step is to deal with reconnection. For WebSockets, we have to handle it ourselves.

There is another issue that affects both technologies - long-running connections.

Both technologies require maintaining long-term open connections to send a continuous stream of events.

Managing such connections, especially at scale, can be a challenge as we quickly run out of resources. Additionally, they may require special configuration, such as extended timeouts, and are more susceptible to any network connectivity issues.

Safety

There is nothing special about security as far as SSE is concerned, as it uses plain old HTTP protocol as the transport medium. All the pros and cons of standard HTTP apply to SSE, it's that simple.

On the other hand, security is one of the biggest drawbacks of the entire WebSocket protocol. First, there is no such thing as a "Same Origin Policy", so there are no restrictions on where we want to connect via WebSocket.

There is even a specific type of attack designed to exploit this vulnerability, namely cross-origin WebSocket hijacking. If you want to dive deeper into the topic of Same Origin Policy and WebSocket, here is an article that may be of interest to you. Other than that, there are no protocol-specific security holes in WebSocket.

I would say that in both cases, all standards and best security practices apply, so be careful when implementing your solution.

Performance

I would say both technologies are equal in terms of performance. Neither technology inherently has theoretical performance limits.

However, I would say that in terms of the number of messages sent per second, SSE can be faster because it follows the fire-and-forget principle. WebSocket also needs to handle the response from the client.

The only thing that can affect the performance of both of them is the underlying client we use in our application and its implementation. Check it out, read the documentation, run custom stress tests, and you might end up learning very interesting things about the tool you're using or the system as a whole.

Message structure

Message structure is probably one of the most important differences between protocols.

As I mentioned above, SSE is a plain text protocol. We can send messages with different formats and content, but ultimately everything ends up in UTF-8 encoded text. There is no possibility of complex formats or binary data.

WebSocket, on the other hand, can handle both text and binary messages. Allows us to send images, audio or just regular files. Keep in mind that processing files can have significant overhead.

Ease of Adoption

Here, the two technologies are at a very similar stage. From an SSE perspective, there are many tools to add WebSocket and server-sent event support (client and server).

Most established programming languages ​​have multiple such libraries. No need to go into too many details. I prepared tables, summarized the basic library, and added WebSockets and SSE support.

Java:

Spring SSE/WebSockets

Quarkus SSE/WebSockets

Scala:

Like SSE/WebSockets

Play/WebSockets

JavaScript

Event Source

Total.js SSE/WebSocekts

Socket.io

Python

Little Star

Fast API

As you can see, if we want to add SSE or WebSockets integration to our application, we have many mature options . Of course, this is just a very small sample from all the libraries; there are many more. The real problem may be finding the one that works best for your specific use case.

Tooling

Automated Testing

As far as I know, there are no automated testing tools for SSE or WebSockets. However, similar functionality can be achieved relatively easily using Postman and collections.

Postman supports server-sent events and WebSockets. By using some magic derived from the Postman collection, you can prepare a set of tests to verify the correctness of your endpoints.

Performance Testing

For performance testing, you can use JMeter or Gadling. As far as I know, these are the two most mature overall performance testing tools. Of course, they all also support SSE (JMeter, Gadling) and WebSockets (JMeter, Gadling).

There are other tools such as sse-perf (SSE only), Testable or k6 (WebSockets only).

Among all these tools, I personally recommend Gattle or k6. Both seem to have the best user experience and are best suited for production.

Documentation

To the extent that there are no dedicated tools for documenting SSE or WebSocket. On the other hand, there is a tool called AsyncAPI which can be used for both concepts in this way.

Unfortunately, OpenAPI does not seem to support SSE or WebSockets.

Summary

As promised, the summary will be quick and easy - see below.

SSE and WebSocket

Comparison table between WebSockets and SSE

I think the above table is a good and compact summary of the topic and the article as a whole.

The most important distinction is the communication direction, as it determines the possible use cases for a specific technology. It will probably have the biggest impact on choosing one of them.

Message structure can also be a very important category when choosing a specific communication method. Allowing only plain text messages is a very important disadvantage of server-sent events.

The above is the detailed content of SSE and WebSocket. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn