Vue2与NetCore用SignalR通信

NetCore启动项配置

 1 using Service.Hubs;
 2 
 3 var builder = WebApplication.CreateBuilder(args);
 4 
 5 // Add services to the container.
 6 
 7 builder.Services.AddControllers();
 8 // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
 9 builder.Services.AddEndpointsApiExplorer();
10 builder.Services.AddSwaggerGen();
11 #region SignalR
12 builder.Services.AddSingleton<VentilatorHub>();
13 builder.Services.AddSignalR();
14 string[] urls = new[] { "http://localhost:8080/" };
15 builder.Services.AddCors(options =>
16 options.AddDefaultPolicy(builder => builder.WithOrigins(urls)
17 .AllowAnyMethod().AllowAnyHeader().AllowCredentials()
18 ));
19 #endregion
20 var app = builder.Build();
21 
22 // Configure the HTTP request pipeline.
23 if (app.Environment.IsDevelopment())
24 {
25     app.UseSwagger();
26     app.UseSwaggerUI();
27 }
28 app.UseCors();
29 app.UseHttpsRedirection();
30 app.UseAuthorization();
31 app.MapControllers();
32 
33 app.MapHub<VentilatorHub>("/Test");注意这里Test,是控制器名字,别写错了
34 
35 app.Run();

控制器循环给前端推送数据

 1 using Microsoft.AspNetCore.Mvc;
 2 using Microsoft.AspNetCore.SignalR;
 3 using Service.Hubs;
 4 using Service.Hubs;
 5 
 6 namespace Example.Controllers
 7 {
 8     [Route("api/[controller]/[action]")]
 9     [ApiController]
10     public class TestController :  ControllerBase
11     {
12         private readonly IHubContext<VentilatorHub> _hubContext;
13         public TestController(IHubContext<VentilatorHub> hubContext)
14         {
15             _hubContext = hubContext;
16         }
17         [HttpGet]
18         public async Task<int> Get()
19         {
20             while (true)
21             {
22                 Thread.Sleep(1000);//这里只是简单测试实现,未做封装,正常推送数据方法应该由服务类执行
23                 await _hubContext.Clients.All.SendAsync("ReceiveMessage", "系统通知", $"北京时间{DateTime.Now}");
24             }
25 
26             return 0;
27         }
28     }
29 }

signalR推送服务类

 1 using Microsoft.AspNetCore.SignalR;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.Linq;
 5 using System.Text;
 6 using System.Threading.Tasks;
 7 
 8 namespace Service.Hubs
 9 {
10     public class VentilatorHub:Hub
11     {
12 
13     }
14 }

前端vue调用

 1   created: function() {
 2     let thisVue = this;
 3     this.connection = new signalR.HubConnectionBuilder()
 4       .withUrl('https://localhost:7013/Test', {
 5         skipNegotiation: true,
 6         transport: signalR.HttpTransportType.WebSockets
 7       })
 8       .configureLogging(signalR.LogLevel.Information)
 9       .build();
10     this.connection.on("ReceiveMessage", function(message) {
11       thisVue.messages.push({ message });
12       console.log({message });
13     });19     this.connection.start();
20   }
21 }
参考地址:https://www.cnblogs.com/netlock/p/13608227.html
https://www.cnblogs.com/aqgy12138/p/12882511.html
posted @ 2023-07-26 17:07  Fast & Furious  阅读(289)  评论(0)    收藏  举报