Asp.Net Core 2.0使用SignalR技术-入门

一、定义Hub集线器

在Asp.Net Core Web项目中已经内置了SignalR的类库可以直接使用。

public class CountService
{
    private int _count = 0;
    public int getLastestCount()
    {
        return _count++;
    }
}
public class CountHub : Hub
{
    private readonly CountService _countService;
    public CountHub(CountService countService)
    {
        _countService = countService;
    }
    public async Task GetLatestCount()
    {
        int count;
        do
        {
            count = _countService.getLastestCount();
            Thread.Sleep(1000);
            await Clients.All.SendAsync("ReceiveUpdate", count);
        } while (count < 10);
        await Clients.All.SendAsync("Finished");
    }
}

 

二、配置启用SignalR

1.注册SignalR

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

    //添加SignalR
    services.AddSingleton();
    services.AddSignalR();
}

2.使用配置SignalR的集线器

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseStaticFiles();
    app.UseMvc();

    //配置SignalR
    app.UseSignalR(routes => routes.MapHub("/count"));
}

3.定义操作控制器,响应处理

    [Route("api/[controller]")]
    [ApiController]
    public class CountController : ControllerBase
    {
        //接受集线器,用于通知客户端
        private readonly IHubContext _countHub;
        public CountController(IHubContext countHub)
        {
            _countHub = countHub;
        }
        [HttpPost]
        public async Task Post()
        {
            await _countHub.Clients.All.SendAsync("someFunc", new { random = "abcd" });
            return Accepted(1);
        }
    }

三、添加客户端使用库

1.在vs中右键添加signarl客户端库,输入@aspnet/signalr@1

Asp.Net Core 2.0使用SignalR技术-入门_第1张图片

Asp.Net Core 2.0使用SignalR技术-入门_第2张图片

2.引用类库文件到html中,编写js链接代码,处理操作逻辑

Asp.Net Core 2.0使用SignalR技术-入门_第3张图片

 

3.执行操作定义代码:


 

 

官方入门教程:https://docs.microsoft.com/en-us/aspnet/core/tutorials/signalr?view=aspnetcore-2.2&tabs=visual-studio

更多:

 Asp.Net Core WebSocket绑定

SingalR自托管(self-host)实例2-实现Wpf客户端和Web客户端矩形同步

SingalR自托管(self-host)实例

你可能感兴趣的:(Asp.net,SignalR)