ASP.NET Core SingleR: First experience and simple project construction

Preface

Ordinary web communication is based on Http requests. The characteristic is that it will be closed after each request, and the delay will be relatively large. If you want to do web games, web chat and other functions, you need to use instant messaging. SignalR is a way of instant communication.

Microsoft Official | ASP.NET Core SignalR Overview

Insert image description here

Insert image description here

Insert image description here

Application scenarios

Our general network requests are to advance the data to the database, and then use the web page request to read the data.

硬件设备
上位机采集程序
数据库
后端
Http网络请求
网页

But for low latency and real-time requirements, this logic is not followed. Because of the real-time nature, it means that the previous data is not important and can be discarded. Just like a live broadcast, unless it is recorded artificially, no one will watch the video in the first minute and can be discarded directly.

硬件设备
上位机采集程序
'直播'数据流
网页

Live broadcast here means real-time data, not video streams like Douyu Live.

What does the SignalR website look like?

Blazor is developed using SignalR

ASP.NET Core Blazor hosting model

Insert image description here
Let’s find a Blazor URL and take a look.

Bootstrap style Blazor UI component library

Insert image description here

The first ASP.NET core SignalR program

Determine SignalR version

Microsoft officially has two SignalRs, one based on .net Framework and one based on .NET Core. According to Microsoft, it should be recommended that we use the core SignalR version

Insert image description here

I found a lot of tutorials on the Internet, but either the version is too old or the answers are incorrect. It's better to follow Microsoft's tutorial and take a look. By the way, I searched for a long time and found Microsoft's latest .net core 8.0 tutorial.

Microsoft official documentation | Tutorial: Getting started with ASP.NET Core SignalR

Insert image description here

Create a new MVC project

According to Microsoft's intention, open an ASP.NET Core Web instead of a Blazor program

Insert image description here
Insert image description here

Add unpkg manager

Insert image description here

After searching online for a long time, I found that I need to install LibMan.

Using LibMan CLI with ASP.NET Core

dotnet tool install -g Microsoft.Web.LibraryManager.Cli

This requires connecting to the external network, and an error may be reported on the internal network.
Insert image description here

Successful installation
Insert image description here

Run it to check the version and see if the installation is successful.

libman --version

Insert image description here

Add client

Insert image description here

Insert image description here
Insert image description here

Insert image description here

Add ChatHub files

Insert image description here

using Microsoft.AspNetCore.SignalR;

namespace SiganlRTest.Hubs
{
    
    
    public class ChatHub : Hub
    {
    
    
        public async Task SendMessage(string user, string message)
        {
    
    
            await Clients.All.SendAsync("ReceiveMessage", user, message);
        }
    }
}


Add SignalR service

Insert image description here

Add web page

@page
<div class="container">
    <div class="row p-1">
        <div class="col-1">User</div>
        <div class="col-5"><input type="text" id="userInput" /></div>
    </div>
    <div class="row p-1">
        <div class="col-1">Message</div>
        <div class="col-5"><input type="text" class="w-100" id="messageInput" /></div>
    </div>
    <div class="row p-1">
        <div class="col-6 text-end">
            <input type="button" id="sendButton" value="Send Message" />
        </div>
    </div>
    <div class="row p-1">
        <div class="col-6">
            <hr />
        </div>
    </div>
    <div class="row p-1">
        <div class="col-6">
            <ul id="messagesList"></ul>
        </div>
    </div>
</div>
<script src="~/js/signalr/dist/browser/signalr.js"></script>
<script src="~/js/chat.js"></script>

Insert image description here
Insert image description here
Copy the Microsoft code into it

"use strict";

var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();

//Disable the send button until connection is established.
document.getElementById("sendButton").disabled = true;

connection.on("ReceiveMessage", function (user, message) {
    
    
    var li = document.createElement("li");
    document.getElementById("messagesList").appendChild(li);
    // We can assign user-supplied strings to an element's textContent because it
    // is not interpreted as markup. If you're assigning in any other way, you 
    // should be aware of possible script injection concerns.
    li.textContent = `${
      
      user} says ${
      
      message}`;
});

connection.start().then(function () {
    
    
    document.getElementById("sendButton").disabled = false;
}).catch(function (err) {
    
    
    return console.error(err.toString());
});

document.getElementById("sendButton").addEventListener("click", function (event) {
    
    
    var user = document.getElementById("userInput").value;
    var message = document.getElementById("messageInput").value;
    connection.invoke("SendMessage", user, message).catch(function (err) {
    
    
        return console.error(err.toString());
    });
    event.preventDefault();
});

Run tests

Insert image description here

Browser Websocket debugging

Insert image description here
Insert image description here
Sent message
Insert image description here
Received message
Insert image description here
We see that the message contains a lot of information, so what does it mean? Here you have to check out the official Github repository of SignalR.

SignalR Hub Protocol

type=1

Insert image description here

Just translate it

  • type: When it is 1, it is used for message interaction. Not only may it be used to ensure that the network is stable
  • invocationId: optional, ID used to distinguish messages
  • target: trigger string, similar to Token in MQTT
  • arguments: message load, similar to Payload in MQTT
  • streamIds: optional, unique ID of the communication

type=6

When type is 6, it is used to ping the network situation.

Insert image description here

When Type is other

Type has a total of 1-9, 9 methods. I will not explain them here.

Summarize

Next I will study the client-side and server-side development of ASP.NET Core. There is not a lot of information online, so I can only do some research on my own.

Guess you like

Origin blog.csdn.net/qq_44695769/article/details/135615601