zoukankan      html  css  js  c++  java
  • netcore3.1 webapi使用signalR

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

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

    img

    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项目 用来模拟前端

    img

    将图片上的这三个文件里面的代码替换成我的 其中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 + "
    来源是" + 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的方式启动

    img

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

    img

    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}", "只给你发");		
            }	
        }}
    

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

    测试一下给指定人发

    img

    测试一个给所有人发

    img

    ok啦~

    -------------------------------------------

    学而不思则罔,思而不学则殆

    你好,我是【咬轮猫】

    -------------------------------------------

  • 相关阅读:
    CNN做序列标注问题(tensorflow)
    对于梯度消失和梯度爆炸的理解
    LSTM(长短期记忆网络)及其tensorflow代码应用
    Python之禅
    Python namedtuple
    Linux里的2>&1
    PySpark笔记
    平衡二叉树,B树,B+树
    lzo文件操作
    Hadoop的Shell命令
  • 原文地址:https://www.cnblogs.com/Hero-/p/13490647.html
Copyright © 2011-2022 走看看