前言

  今天尝试了一下signalR,感觉还不错,因为暂时用不到,就写一篇博文来记录搭建过程,以免以后给忘了,基于官方文档写的,不过官方没有webapi调用例子,就自己写了一下,大神勿喷

使用

1.创建一个netcore3.1 webapi程序,nuget引用一下Microsoft.AspNetCore.SignalR,我这里是1.1.0版本

2.创建一个类 SignalRHub.cs 用来自定义集线器 继承自SignalR的集线器 代码如下

using Microsoft.AspNetCore.SignalR;
using System;
using System.Threading.Tasks;
namespace SignalR_Server{
public class SignalRHub:Hub {
public async Task sendall(string user, string message)
{
await Clients.All.SendAsync("toall",user,message,"给所有人发");
}
/// <summary>
/// 重写集线器连接事件
/// </summary>
/// <returns></returns>
public override Task OnConnectedAsync()
{
Console.WriteLine($"{Context.ConnectionId}已连接");
return base.OnConnectedAsync();
}
/// <summary>
/// 重写集线器关闭事件
/// </summary>
/// <param name="exception"></param>
/// <returns></returns>
public override Task OnDisconnectedAsync(Exception exception)
{
Console.WriteLine("触发了关闭事件");
return base.OnDisconnectedAsync(exception);
}
}}

3.修改Startup中的ConfigureServices方法 代码如下

public void ConfigureServices(IServiceCollection services)
{
//配置SignalR服务 配置跨域
services.AddCors(options => options.AddPolicy("CorsPolicy",
builder =>
{
builder.AllowAnyMethod()
.AllowAnyHeader()
.WithOrigins("http://localhost:51083")
.AllowCredentials();
}));
services.AddSignalR();
services.AddControllers(); }

4.修改Startup中的Configure方法 代码如下

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
//使用跨域
app.UseCors("CorsPolicy");
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
//使用集线器
endpoints.MapHub<SignalRHub>("/chatHub");
});
}

5.因为要实现前后端分离 这里我们再打开一个vs 创建一个mvc项目 用来模拟前端

将图片上的这三个文件里面的代码替换成我的 其中signalr.js是官方的 下载方式如下

(1)在“解决方案资源管理器” 中,右键单击项目,然后选择“添加” >“客户端库” 。

(2)在“添加客户端库” 对话框中,对于“提供程序” ,选择“unpkg” 。

(3)对于“库” ,输入 @microsoft/signalr@3,然后选择不是预览版的最新版本

(4)选择“选择特定文件” ,展开“dist/browser” 文件夹,然后选择“signalr.js” 和“signalr.min.js”

(5)将“目标位置” 设置为 wwwroot/js/ ,然后选择“安装”

该方法复制于弱水三千 只取一瓢饮

感谢老哥 大家也可以参考官方文档进行下载

剩下的两个文件代码很简单 我就不多说了

chat.js

"use strict";
var connection = new signalR.HubConnectionBuilder().withUrl("http://localhost:5000/chatHub").build();
//Disable send button until connection is establisheddocument.getElementById("sendButton").disabled = true;
//这个可以不一致
connection.on("toall", function (user, message,test)
{
var msg = message;
var encodedMsg = user + " says " + msg + "\n来源是" + test;
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("sendall", user, message).catch(function (err) {
return console.error(err.toString());
});
event.preventDefault();
});

Index.cshtml

@page<div class="container">
<div class="row"> </div>
<div class="row">
<div class="col-2">用户名</div>
<div class="col-4"><input type="text" id="userInput" /></div>
</div>
<div class="row">
<div class="col-2">要发送的消息</div>
<div class="col-4"><input type="text" id="messageInput" /></div>
</div>
<div class="row">
</div>
<div class="row">
<div class="col-6">
<input type="button" id="sendButton" value="发送消息" />
</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.js"></script><script src="~/js/chat.js"></script>

然后启动服务端和客户端 注意这里服务端我们使用kestrel的方式启动

启动成功可以看到控制台成功打印出了连接的用户id 测试发消息也正常

6.现在我们要通过api的方式进行请求了 在服务端新建一个控制器SignalRTestController 代码如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Ladder.Data;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
namespace SignalR_Server.Controllers{
[Route("api/[controller]")]
[ApiController]
public class SignalRTestController : ControllerBase {
private readonly IHubContext<SignalRHub> _hubContext;
public SignalRTestController(IHubContext<SignalRHub> hubClients)
{
_hubContext = hubClients;
}
[HttpGet("index")]
public string index()
{
return "HELLO World";
}
[HttpGet("sendall")]
public void SendAll()
{
//给所有人推送消息
_hubContext.Clients.All.SendAsync("toall", "后端","你好","给所有人发");
}
[HttpGet("sendToUser")]
public void SendToUser(string user)
{
//给指定人推送消息
_hubContext.Clients.Client(user).SendAsync("toall", "后端", $"你好{user}", "只给你发");
}
}}

然后启动服务端和客户端 将客户端的页面打开两个

测试一下给指定人发

测试一个给所有人发

ok啦~

最新文章

  1. 通向高可扩展性之路(WhatsApp篇)---- 脸书花了190亿买来的WhatsApp的架构
  2. sublime2的快捷键
  3. 【转】七年IT经验的七个总结
  4. Unity3D 给模型偏移纹理
  5. 【摘要】多线程 - BeginInvoke异步调用
  6. cisco nat
  7. C#多线程与UI响应 跨线程更新UI
  8. 使用jquery实现局部刷新DIV
  9. 【转】COCOS2D-X之不断变化的数字效果Demo
  10. 怎么让自己的java系统使用支付接口
  11. MD5方法代码(生成小写的md5) C#版本
  12. POJ训练计划2299_Ultra-QuickSort(归并排序求逆序数)
  13. 用django搭建一个简易blog系统(翻译)(二)
  14. 兼容ie6的图片垂直居中
  15. 学习笔记——工厂模式Factory
  16. FOJ 2203 单纵大法好
  17. CodeForces 544C (Writing Code)(dp,完全背包)
  18. C# EF使用SqlQuery直接操作SQL查询语句或者执行过程
  19. # 20175333曹雅坤《Java程序设计》第2周学习总结
  20. MS17-010 漏洞研究——免考课题 20155104 赵文昊

热门文章

  1. Java系列教程-MyBatis 3.5.5 教程目录
  2. C++ 虚函数的内部实现
  3. Mysql之案例分析(一)
  4. 基于Hive进行数仓建设的资源元数据信息统计:Spark篇
  5. [状压DP]子矩阵
  6. Redis解读(2):Redis的Java客户端
  7. Typescript进阶之路
  8. Java后端进阶-消息中间件
  9. 解决SQLPLUS无法使用上下箭头
  10. SpringBoot-如何设计优秀的后端接口?