[.Net Core学习二]实时通讯 SignalR

1.添加客户端库

[.Net Core学习二]实时通讯 SignalR_第1张图片[.Net Core学习二]实时通讯 SignalR_第2张图片

2.创建SignalR中心

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

3.添加配置 将 SignalR 添加到 ASP.NET Core 依赖关系注入系统和中间件管道

Startup中ConfigureServices加入 services.AddSignalR(); Configure加入  app.UseSignalR(routes => {routes.MapHub("/chatHub");});

4.添加Razor页面

 
 
User..........
Message...

 

    5.添加js

    "use strict";
    
    var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
    
    //Disable send button until connection is established
    document.getElementById("sendButton").disabled = true;
    
    connection.on("ReceiveMessage", function (user, message) {
        var msg = message.replace(/&/g, "&").replace(//g, ">");
        var encodedMsg = user + "[" + new Date().toLocaleString() + "] " + msg;
        var li = document.createElement("li");
        li.textContent = encodedMsg;
        document.getElementById("messagesList").appendChild(li);
    });
    
    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();
    });

    6.结果

    [.Net Core学习二]实时通讯 SignalR_第3张图片

    你可能感兴趣的:(Core)