Understanding the benefits of SignalR

SignalR is a feature in ASP.NET Core that we can use to create a real-time API. A real-time API is where data is pushed to connected clients when the data arrives at the server.

An example use case of a real-time API is on Twitter, where new tweets automatically appear in our feed as they are tweeted. Chat apps are another common example where we can get messages from other users immediately after they send messages.

Real-time APIs are different from REST APIs. With a REST API, the client needs to make a request to get new data that's available on the server. When there is no updated data, the response data in this type of request isn't needed by the client because it already has a copy of that data. So, this is an inefficient and slow approach to updating the client with new data. SignalR solves this efficiency problem because new data can be pushed from the server to clients.

So, the key feature that SignalR has that a REST API hasn't got is the ability to push data from the server to the client. It uses web sockets as the transport mechanism, if available in the browser and web server, and falls back on other mechanisms if not.

The Web sockets technology allows an open two-way interactive communication session between the user's browser and a server using a TCP socket. A TCP socket is a lower-level and faster mechanism than HTTP. This technology is available in the latest versions of all modern browsers, including IE.

It sounds like web sockets do everything that a REST API can do, as well as being faster. Why wouldn't we use a real-time API for all communication with the server and not use a REST API at all? Well, a few reasons are as follows:

  • There is nothing like an HTTP status code in a web socket message. So, how does the client know that a form that has been submitted has invalid data? Or maybe that the user isn't authorized to submit the form? In the web socket world, we'd need to implement something such as an HTTP status code ourselves.
  • HTTP has other features such as caching and compression that aren't available as standard for web sockets.
  • Web sockets are stateful and there is no standard way to scale them horizontally. A REST API is stateless and therefore can be easily scaled across multiple web servers.

So, in our app, we are going to use SignalR to create a real-time API where we need to push data from the server to the client. We'll start this implementation in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.255.113