Real-time Library of ASP. SignalR--Pre-knowledge

Source: Internet
Author: User
Tags documentation
Outline

This series is divided into 2-3 articles.

    • The first article introduces SIGNALR's preliminary knowledge and principles
    • It then introduces SIGNALR and how to use SIGNALR in ASP.

The directory of this article is as follows:

    • Real-time web brief
    • Long Polling
    • SSE (Server Sent Events)
    • Websocket

Real-time web brief

Everyone has seen and used real-time web, such as Web-page instant messaging, live streaming, web games, stock dashboards, and more.

This is how traditional Web applications work:

The browser sends an HTTP request to the ASP. NET Core Web server, and if all goes well, the Web server processes the request and returns the response, which in payload contains the requested data.

But this way of working is not for real-time web. The live web requires the server to proactively send messages to the client (which can be a browser):

The Web server can proactively notify the client of changes to the data, such as a new conversation message.

"Bottom-up" technology

SIGNALR uses three "bottom-up" technologies to implement the real-time web, which are long Polling, Server Sent Events and Websocket.

First, you need to know what Ajax is. This is not introduced.

Long pollingpolling

Before introducing long Polling, first introduce Polling.

Polling is a dumb way to implement the real-time web by periodically sending requests to the server to see if the server's data is changing.

If the server data does not change, then return 204 no Content; If there is a change, send the latest data to the client:

Here is an implementation of polling, which is very simple:

Just look at the controller's Get method. Using MyService, it is a singleton in the project. Its approach is simple:

MyService is doing a global count, and its getlatestcount will return the latest count.

The code inside the controller means: if Count > 6 returns an object containing the value of count and the ID passed in; If Count > 10, also return a finished flag.

Look at the front-end code:

is also very simple, click on the button to send a request periodically, if there is a result to display the latest count value; If there is a finished flag, the latest value is displayed and is closed.

Note that the fetch API is used here.

When you run the project, Count > 6:

End of Count > 10:

This is polling, very simple, but a waste of resources.

SIGNALR did not adopt the polling technique .

Long Polling

Long Polling and Polling have a similar place where clients are sending requests to the server. But the difference is: If the server does not have new data to send to the client, then the server will continue to remain connected until new data is generated, the server to return the new data to the client .

If there is no response within a period of time after the request is issued, the request times out. At this point, the client will make a request again .

Example, the controller's code changes slightly:

The purpose of the change is to keep the connection open until the data that meets the requirements is present.

The front end also has some changes:

The Pollwithtimeout method uses race and returns a time-out error if the request does not respond after more than 9 seconds.

Poll inside, if the request returns a result of 200, then the UI is updated. However, if there is no finished flag, continue to make the request.

Run:

You can see that there is only one request, the request takes a long time, and the identity connection is open for a long time.

One thing to note here is that the server's timeout length may be different from the browser's timeout.

The polling and long polling described in the front are HTTP requests, which are not really suitable.

Here's a little bit better technology:

Server Sent Events (SSE)

With SSE , the Web server can send data to the browser at any time, which can be called push. and the browser listens to incoming information, which, like streaming data, remains open until the server actively shuts it down .

The browser uses an object called EventSource to process the transmitted information .

Example, this differs from the previous code in many places, using the reponse:

Note that the SSE return data can only be a string, but also with data: Beginning, followed by a newline symbol, otherwise eventsource will fail.

Client:

This is very simple, using the EventSource onmessage event. The previous request waits until the response is returned, and then a request is made.

Run:

This eventsource is much better than polling and long polling.

It has the following advantages: the use of simple (HTTP), automatic re-connection, although not support the old browser but it is easy to polyfill.

And the disadvantage is: many browsers have the maximum number of concurrent connections limit, can only send text messages, one-way communication.

Web Socket

A WEB socket is another TCP protocol that differs from HTTP. It makes it possible for interactive communication between the browser and the server. With WebSocket, messages can be sent from the server to the client, or from the client to the server, without the delay of HTTP. When the information flow is not complete, the TCP socket is usually kept open.

When using a line browser, SIGNALR uses a web Socket in most cases, which is the most efficient way to transfer.

Full-Duplex communication : Clients and servers can send messages to each other at the same time.

and is not affected by the SSE of that browser connection limit (6), most browsers on the number of web socket connection limit is 50.

Message type: Can be text and binary, WEB sockets also support streaming media (audio and video).

In fact, the normal HTTP request also uses the TCP Socket. The WEB socket standard uses a handshake mechanism to upgrade a socket for HTTP to a WebSocket socket that uses the WS protocol .

Life cycle

The life cycle of a WEB socket is this:

Everything happens in the TCP socket, first a regular HTTP request will ask the server to update the socket and negotiate, this is called the HTTP handshake. The message can then be transferred back and forth in the socket until the socket is actively closed. In the active shutdown, the reason for the shutdown will also be communicated.

HTTP handshake

Every web socket starts with a simple HTTP socket.

The client first sends a GET request to the server to request an upgrade socket.

If the server agrees, the socket becomes a Web socket from this point on.

An example of this request is as follows:

The first line indicates that this is an HTTP GET request.

Upgrade This header indicates the request to upgrade the socket to the web socket.

Sec-websocket-key, it is also important to prevent caching problems, see official documentation for details.

After the server understands and agrees to the request, it responds as follows:

Returns a 101 status code that represents the switching protocol.

If the return is not 101, then the browser will know that the server does not have the ability to handle websocket.

There are also upgrade:websocket in the header.

Sec-websocket-accept is operated in conjunction with Sec-websocket-key, please refer to the official documentation for details.

Message type

The message type of the WEB socket can be text, binary. Also includes the control class message: Ping/pong, and shutdown.

Each message consists of one or more frame:

All of the frames are binary. So the text will be converted into binary first.

Frame has a number of header bits.

Some can indicate whether the frame is the last frame of the message;

Some can represent the type of message.

Some can indicate whether the message is cloaked. Client-to-server messages are cloaked, in order to prevent cache poisoning (replacing the cache with malicious data).

Some can set the length of the payload, payload will occupy the rest of the frame.

In fact, you will not be able to observe frame, it is processed in the background, you can see the complete message.

But when the browser is debugging, you see that the frame is passing in instead of the entire message.

Take a look at the following example:

The WebSocket is built into the ASP. NET core project, but you need to configure and use this middleware in startup:

Here we set the ping at every 120 seconds. It also sets the cache size used to receive and resolve frame. In fact, these two values are the default values.

Modified Controller:

The httpcontextaccessor needs to be injected here. Then determine whether the request is a websocket request, and if so, the client will receive a reply, and the socket will be upgraded. After the upgrade returns a WebSocket object, then I send events through it. Then I closed the websocket and pointed out the reason normalclosure.

Then look at the Sendevents method:

The focus here is on the SendAsync method of the WebSocket object. I need to convert the data into buffer for transmission. The data type is text. See the documentation for specific parameters.

Look at the client:

Also very simple, here is a WebSocket object, note that here the URL begins with ws instead of HTTP, and a WSS, first when it is HTTPS with HTTP.

Then EventHandler and SSE are similar. The JSON data returned needs to be parse before it can be used.

This article first to this, and then introduce the next signalr and usage can be.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.