SignalR实时聊天

SignalR实时聊天1 创建 Web 项目 选择 Web 应用程序 以创建使用 RazorPages 的项目 然后选择 创建 2 添加 SignalR 客户端库 SignalR 服务器库包含在 ASP NETCore3 0 共享框架中 JavaScript 客户端库不会自动包含在项目中 对于此教程 使用库管理器 LibMan 从 unpkg 获取客户端库 unpkg 是一个内容分发网络 CDN 可分发在 npm 即 Node js 包管理器 中找到的任何内容 在 解决方案资源管理器 中 右键

1.创建 Web 项目。

2.添加 SignalR 客户端库。

SignalR 服务器库包含在 ASP.NET Core 3.0 共享框架中。 JavaScript 客户端库不会自动包含在项目中。 对于此教程,使用库管理器 (LibMan) 从 unpkg 获取客户端库。 unpkg 是一个内容分发网络 (CDN),可分发在 npm(即 Node.js 包管理器)中找到的任何内容。

  • 在“解决方案资源管理器”中,右键单击项目,然后选择“添加”>“客户端库” 。
  • 在“添加客户端库”对话框中,对于“提供程序”,选择“unpkg”。
  • 对于“库”,输入 @microsoft/signalr@latest。
  • 选择“选择特定文件”,展开“dist/browser”文件夹,然后选择“signalr.js”和“signalr.min.js”。
  • 将“目标位置”设置为 wwwroot/js/signalr/,然后选择“安装”。
    在这里插入图片描述

  • 在 SignalRChat 项目文件夹中,创建 Hubs 文件夹。
  • 在 Hubs 文件夹中,使用以下代码创建 ChatHub.cs 文件 :
using Microsoft.AspNetCore.SignalR; using System.Threading.Tasks; namespace SignalRChat.Hubs { 
    public class ChatHub : Hub { 
    public async Task SendMessage(string user, string message) { 
    await Clients.All.SendAsync("ReceiveMessage", user, message); } } } 

ChatHub 类继承自 SignalR Hub 类。 Hub 类管理连接、组和消息。

可通过已连接客户端调用 SendMessage,以向所有客户端发送消息。 本教程后面部分将显示调用该方法的 JavaScript 客户端代码。 SignalR 代码是异步模式,可提供最大的可伸缩性。

4.配置项目以使用 SignalR。

必须将 SignalR 服务器配置为将 SignalR 请求传递给 SignalR。

  • 将以下突出显示的代码添加到 Startup.cs 文件。
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using SignalRChat.Hubs; namespace SignalRChat { 
    public class Startup { 
    public Startup(IConfiguration configuration) { 
    Configuration = configuration; } public IConfiguration Configuration { 
    get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { 
    services.AddRazorPages(); services.AddSignalR(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { 
    if (env.IsDevelopment()) { 
    app.UseDeveloperExceptionPage(); } else { 
    app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { 
    endpoints.MapRazorPages(); endpoints.MapHub<ChatHub>("/chathub"); }); } } } 

这些更改将 SignalR 添加到 ASP.NET Core 依赖关系注入和路由系统。

5.添加 SignalR 客户端代码

  • 使用以下代码替换 Pages\Index.cshtml 中的内容:
@page <div class="container"> <div class="row">&nbsp;</div> <div class="row"> <div class="col-2">User</div> <div class="col-4"><input type="text" id="userInput" /></div> </div> <div class="row"> <div class="col-2">Message</div> <div class="col-4"><input type="text" id="messageInput" /></div> </div> <div class="row">&nbsp;</div> <div class="row"> <div class="col-6"> <input type="button" id="sendButton" value="Send Message" /> </div> </div> </div> <div class="row"> <div class="col-12"> <hr /> </div> </div> <div class="row"> <div class="col-6"> <ul id="messagesList"></ul> </div> </div> <script src="~/js/signalr/dist/browser/signalr.js"></script> <script src="~/js/chat.js"></script> 

前面的代码:

  • 创建名称以及消息文本的文本框和“提交”按钮。
  • 使用 id=“messagesList” 创建一个列表,用于显示从 SignalR 中心接收的消息。
  • 包含对 SignalR 的脚本引用以及在下一步中创建的“chat.js”应用程序代码。
  • 在 wwwroot/js 文件夹中,使用以下代码创建 chat.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, "<").replace(/>/g, ">"); var encodedMsg = user + " says " + 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.运行应用

  • 按 Ctrl+F5 可运行应用而不进行调试。
  • 从地址栏复制 URL,打开另一个浏览器实例或选项卡,并在地址栏中粘贴该 URL。
  • 选择任一浏览器,输入名称和消息,然后选择“发送消息”按钮。
  • 两个页面上立即显示名称和消息。
    在这里插入图片描述

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/175812.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月26日 下午11:22
下一篇 2026年3月26日 下午11:22


相关推荐

  • TIFF文件解析

    TIFF文件解析TIF 文件是一种标签标记文件 为什么这么说呢 它的文件的构成方式就是根据 Tag 来标记的 同时还可以记录地理信息 坐标 投影等信息 非常方便在 GIS 领域使用 网上关于 TIFF 文件的介绍也是不少 今天我主要是把我之前使用 C 解析 TIF 文件的过程记录下来 1 定义 TIFF 文件的结构体 TIFF 文件的数据结构 typedefstruc FILE pfile

    2026年3月20日
    2
  • 串口转网口的线怎么做

    串口转网口的线怎么做串口 nbsp 1 nbsp 2 nbsp 3 nbsp 4 nbsp 5 nbsp 6 nbsp 7 nbsp 8 nbsp 9 nbsp rj 45 nbsp 1 nbsp 2 nbsp 3 nbsp 4 nbsp 5 nbsp 6 nbsp 7 nbsp 8 1 是棕色按照 568B 反拧 nbsp 串口 rj45 nbsp 1 4 5 nbsp 2 7 nbsp 3 6 nbsp 4 3 nbsp 7 1 nbsp 8 8 nbsp 9 2 nbsp

    2026年3月26日
    3
  • HTML5注释快捷键

    HTML5注释快捷键注释快捷建:Ctrl+/取消注释只需再次点击这个组合键即可。

    2022年4月29日
    61
  • mysql如何添加字段_mysql如何增加字段

    mysql如何添加字段_mysql如何增加字段mysql 增加字段的方法 createtablei name idint namevarchar 20 表示增加 id 和 name 字段 mysql 增加两个字段 mysql gt createtablei name idint namevarchar 20 QueryOK 0rowsaffecte 0 13sec mysql gt altertabl

    2026年3月17日
    2
  • oracle r修改表名,oracle中修改表名「建议收藏」

    oracle r修改表名,oracle中修改表名「建议收藏」<<>>answer1:ALTERTABLEold_table_nameRENAMETOnew_table_name;(大写为系统命令)answer2:SQL>selecttnamefromtab;TNAME——————————TESTSQL>renametesttotemp;Tablere…

    2022年5月17日
    44
  • 数据库设计——关系数据理论(超详细)「建议收藏」

    数据库设计——关系数据理论(超详细)「建议收藏」问题——什么是一个好的数据库逻辑设计●关系型数据库逻辑设计:➠针对一个具体问题应如何构造一个适合于它的数据模式,即应构造几个关系,每个关系由哪些属性组成等eg:?这样的设计是一个好的设计吗?观察这个表所对应的一个实例(在某个时刻student模式所对应的一个实际的数据情况):如有若干个学生,他们都为’计算机系’,系主任为’张明’,选修了’C1’课程,得到各自的成绩☟☞关系模式STUDENT(Sno,Sdept,Mname,Cno,Grade)中存在的问题:☜1、数据冗余太大,浪费存储空间如

    2022年10月9日
    7

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号