其他分享
首页 > 其他分享> > Signar即时通讯的简单应用

Signar即时通讯的简单应用

作者:互联网

实时 Web 功能使服务器端代码能够将内容推送到客户端。  实现简单聊天功能

1、创建Razor模板应用   

2、创建Signar客户端

3、创建signar中心:用作客户端和服务端通信的高级管道

 1 using Microsoft.AspNetCore.SignalR;
 2 
 3 namespace SignalRChat.Hubs
 4 {
 5     public class ChatHub : Hub
 6     {
 7         public async Task SendMessage(string user, string message)
 8         {
 9             await Clients.All.SendAsync("ReceiveMessage", user, message);
10         }
11     }
12 }

可通过已连接客户端调用 SendMessage,以向所有客户端发送消息

4、配置Signar  

using SignalRChat.Hubs;

builder.Services.AddSignalR();

app.MapHub<ChatHub>("/chatHub");

 

  将 SignalR 添加到 ASP.NET Core 依赖关系注入和路由系统

5、创建chat.j文件    

"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(); });

 

  6.效果

 

标签:function,connection,即时通讯,getElementById,Signar,user,应用,message,document
来源: https://www.cnblogs.com/Join-Lzy-666/p/16464380.html