Since SignalR, as a separate push system, is separated from the business system, a business system is simulated here and a.net Core APP project is created

Emulation implements a login function

Our login is very simple. When we enter the system, if we detect that the user has not logged in, we will jump to the login page, and the user only needs to enter the user name and click login

  • Configure the ConfigServices method to view the code
  services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
  .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, cookieOption =>
  {
      cookieOption.LoginPath = "/Account/Login";
      cookieOption.AccessDeniedPath = "/Account/Login";
  });Copy the code
  • Configure the Config method to configure the authentication and authorization request pipeline viewing code
  app.UseRouting();
  app.UseAuthentication();
  app.UseAuthorization();Copy the code
  • Receive login POST request, write cookies, jump to view the code

Front-end page implementation

First in the Layout page to introduce the required JS files (vue, SignalR, MSgPack5, SignalR-protocol-MSgpack) to view the code

Encapsulate SignalR connection-related JS

Signalr client JS creates a connection, listens for push, and encapsulates the backend JS

/** * Initializing connection * @param {object} option parameter * @param {string} option.url Url address of connection * @param {string} option.loggingLevel Log level: Error * @param {number} option.delay Delay connection: 3000 ms * @param {function} option.onStarted Trigger * @param * @param {function} option.offLine trigger * @returns {object} connection instance */ function initSignalr(option) { var config = Object.assign(true, { loggingLevel: signalR.LogLevel.Error, delay: 3000, url: '' }, option); var connection = new signalR.HubConnectionBuilder() .configureLogging(config.loggingLevel) .withUrl(config.url, { accessTokenFactory: option.accessTokenFactory }) .withHubProtocol(new signalR.protocols.msgpack.MessagePackHubProtocol()) .withAutomaticReconnect([0, 2000, 5000, 10000, 20000]) .build(); connection.onreconnecting(function (info) { console.info('----------------------------------signalr-- onreconnecting', info); }); connection.onclose(function (err) { console.info('--------------------------------signalr-- onclose', err); }); connection.on('OnNotify', config.onNotify); connection.on('OnLine', config.onLine); connection.on('OffLine', config.offLine); setTimeout(function () { connection.start().then(function (data) { option.onStarted && option.onStarted(data); }).catch(function (error) { console.error(error.toString()); }); }, option.delay); return connection; }Copy the code

  • Then import the js above in Home/ index.cshtml
  • After the page is loaded, the call initialization (vUE was used in this case) will pop up and ask the user to enter the group to join, either none or multiple groups
function initConnect() { $("#collectionUserInfo").modal({ keyboard: false, show: true, backdrop: 'static' }) $('#collectionUserInfo').on('hidden.bs.modal', function () { var groups = $("#groups").val()||''; connect=initSignalr({ delay: 0, url:`${notifyUrl}notify-hub? userId=${vm.userInfo.userName}&group=${groups}`, loggingLevel: signalR.LogLevel.Error, onNotify: dealNotify, onLine: function (data) { if (data.IsFirst) { getOnlineUsers(); } getOnlineGroups(); Vm. logs.push(' new connection online: ${json.stringify (data)} '); }, offLine: function (data) { if (data.IsLast) { getOnlineUsers(); } getOnlineGroups(); Vm.logs.push (' connection offline: ${json.stringify (data)} '); }, onStarted: function () { getOnlineUsers(); getOnlineGroups(); vm.$set(vm.userInfo, 'connectionId', connect.connectionId); vm.$set(vm.userInfo, 'groups', groups); Vm.logs.push (' connection successful '); }}); })}Copy the code

The onNotify method, if you’re careful, you’ll see the onNotify method inside, and all push will eventually be called to the onNotify method for distribution. Check the code offLine, which will be triggered when a client is offLine. Data contains the user Id, connection Id, and whether the user has the last connection. You can use the code onLine as required, which will be triggered when the user is connected. Data contains the user Id, connection Id, whether the user’s first connection (used for logical processing after the user goes online), which can be used to view the code onStarted as needed. When the successful connection is triggered, it can be used to do some business logic processing after the connection

Get the current user information and online list

After the user connection is successful, obtain the information of the current online user, user group, and current user, and set it to vUE data to view the code

Simulate a task assignment

In the project center, click the “simulated push backlog” button, and a code message will be pushed to the current user’s group. You can log in to different accounts and open multiple TAB pages to experience the location of event code and view the code

assignTaskToUser: function () {
    var that = this;
    $.ajax({
        type: 'POST',
        url: '/api/ServerProxy/AssignTaskToUser',
        data: {
            groups:that.userInfo.groups
        }
    })
},Copy the code

Corresponding push parsing code

First, when a push comes in, the onNotify method is first advanced, and then assigned to different JS methods according to different types

Look at the code

rendering

Simulate sending a message

Message sending, you can select groups, people for message sending end code parsing end

Login mutex

Mutually exclusive login means that when an account logs in from computer A and then logs in from computer B, the last login excludes the first login, that is, the account on computer A is forced to log out

First log in with Google Chrome, enter username xiexingen, and then connect

Then use 360 Haste browser to log in and enter the user name xiexingen. At this time, you will find that the login in Google Chrome has exited, as shown in the picture

Necessary: different browsers, the same user, for example: the same browser, different TAB does not count (can share cookies)

File download (specified connection push)

Scene file download, the user chose to thousands of files on the page, and then click on the download package, this time may need long time to respond back, so if the user has been waiting for this time is clearly wrong, so, when users click on the download, the back-end to enable a background thread to packaging, compression, and then return immediately; The user can continue to operate, when the server is packaged and pushed to the client, the user can click download. This applies to both cases

  1. Single link push users open multiple TAB pages, download files on one of them, if the back-end push, directly to the user, obviously inappropriate; The right thing to do is only to push the TAB page of the operation, which requires that business API calls to the server, need to connect the current TAB page corresponding id sent to the server, the server after processing business, call to push server, tell only push server push me to give you the connection of the client, so you can specify the connection to push.
  2. It’s rare for a single user to exclude other connections from a particular connection, and tell the push server to push all connections except for that particular connection to that user

Simulation operation

Click the “package download file” button in the first image, and the current page will be pushed to download the file

Click the button of “Push current user to update other pages” in Figure 2, and you will find that other tabs besides the current TAB page have also received push messages, as shown below

So far, signalR related articles is the end of this, the next article about personal experience and there are some problems.

Quick navigation

The title

content
The index

.NET Core 3.0 Signalr – Implementation of a business push system
In the previous

Net Core 3.0 SignalR-07 Service implementation – Server to customize the management group, user, connection
The next article

.NET Core 3.0 SignalR-09 to be improved & AC
The source address

The source code
The official documentation

The official documentation