使用SignalR asp.net core通信 (二)使用分组

使用分组指定条件发送消息

服务端

创建强类型SignalR
IChatClient.cs

/// <summary>
/// 商户消息 强类型中心
/// </summary>
public interface IChatClient
{
    /// <summary>
    /// 接收消息
    /// <para>客户端监听方法名为ReceiveStoreMessage</para>
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    Task ReceiveStoreMessage(MessageDto dto);
}

MessageDto.cs

/// <summary>
/// 消息
/// </summary>
public class MessageDto
{

    public MessageDto()
    {
        CreateTime = DateTime.Now;
    }

    /// <summary>
    /// 消息标题
    /// </summary>
    public string Title { get; set; }

    public string Message { get; set; }

    public int Type { get; set; }

    /// <summary>
    /// 创建时间
    /// </summary>
    public DateTime CreateTime { get; set; }
}

现在修改ChatHub.cs文件

public class ChatHub:Hub<IChatClient>
{
    /// <summary>
    /// 重写 连接
    /// </summary>
    /// <returns></returns>
    public override async Task OnConnectedAsync()
    {
         var data = Context.GetHttpContext().Request.Query["token"];
            if (!string.IsNullOrEmpty(data))
            {
                //这里根据获取到的token获取信息 根据指定的数据进行分组 例如租户id
                var groupName = "group_1";
                await Groups.AddToGroupAsync(Context.ConnectionId, groupName);
            }
            await Task.CompletedTask;
    }
}

接口调用

public class ChatController:ControllerBase
{

    private readonly IHubContext<ChatHub,IChatClient> _chatHubContext;
    public ChatController(IHubContext<ChatHub,IChatClient> chatHubContext)
    {
        _chatHubContext = chatHubContext;
    }
    [Route("v1/SendMessage")]
    public async Task SendMessage()
    {
        var data = new MessageDto { Title="您收到一条验证消息",Message = "消息内容",Type = 1 };
        //这里可写获取需要发送分组的名称 
        var groupName = "group_1";
        await _chatHubContext.Clients.Group(groupName).ReceiveStoreMessage(data);

    }
}

客户端

需要修改 signalR.js文件

//引入安装的signalr包
import * as signalR from '@aspnet/signalr'
const signal = new signalR.HubConnectionBuilder()
    .withUrl('http://localhost:52970/chathub?token='+token)//服务器地址
    .build()
export default {
    install: function(Vue) {
        Vue.prototype.signalr = signal
    }
}

消息接收

this.signalr.on('ReceiveMessage',res=>{
    //可以写业务逻辑
    //res 返回的是后台传过来的数据 MessageDto.cs
    console.log(res);
})

文档资源

posted @ 2020-07-16 17:23  青杉  阅读(505)  评论(1编辑  收藏  举报