web api使用SignalR

Posted 珞檀

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了web api使用SignalR相关的知识,希望对你有一定的参考价值。

1.nuget安装 Microsoft.AspNetCore.SignalR

2.定义一个接口

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SignalRCore.Hubs
{
    public interface IClient
    {
        /// <summary>
        /// 强类型中心
        /// </summary>
        /// <param name="user"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        Task ReceiveMessage(string user, string message);

        Task ReceiveMessage(ConcurrentDictionary<string, string> user, string message);

    }
}

3.创建SignalRHub类

using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SignalRCore.Hubs
{
    public class SignalRHub : Hub<IClient>
    {

        private static ConcurrentDictionary<string, string> userIds = new ConcurrentDictionary<string, string>();
        
        /// <summary>
        /// 在所有连接的客户端上调用方法
        /// </summary>
        /// <param name="user"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        [HubMethodName("SendMessage")]
        public async Task SendMessage(string user, string message)
        {
            var Str = Context.ConnectionId;
            await Clients.All.ReceiveMessage(userIds, message);
        }

        /// <summary>
        /// 在调用集线器方法的客户端上调用方法
        /// </summary>
        /// <param name="user"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task SendMessageToCaller(string user, string message)
        {
            await Clients.Caller.ReceiveMessage(user, message);
        }

        /// <summary>
        /// 在所有连接的客户端上调用方法,但调用方法的客户端除外
        /// </summary>
        /// <param name="user"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task SendMessageToOthers(string user, string message)
        {
            await Clients.Others.ReceiveMessage(user, message);
        }

        /// <summary>
        /// 向组的所有客户端发送消息
        /// </summary>
        /// <param name="GroupName"></param>
        /// <param name="user"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task SendMessageToGroup(string GroupName, string user, string message)
        {
            //var item = Context.Items
            await Clients.Group(GroupName).ReceiveMessage(user, message);
        }

        /// <summary>
        /// 向指定用户发送消息
        /// </summary>
        /// <param name="user"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task SendMessageToUser(string user, string message)
        {
            var ConnectionId = Context.ConnectionId;
            var UserId = userIds.Where(x => x.Key != ConnectionId).FirstOrDefault().Key;
            await Clients.Client(UserId).ReceiveMessage(user, message);
        }

        /// <summary>
        /// 处理连接的事件
        /// </summary>
        /// <returns></returns>
        public override async Task OnConnectedAsync()
        {
            //Context.Items.Add()
            var Id = Guid.NewGuid().ToString();
            var ConnectionId = Context.ConnectionId;

            userIds.TryAdd(ConnectionId, Id);
            await base.OnConnectedAsync();
        }

        /// <summary>
        /// 断开连接
        /// </summary>
        /// <param name="exception"></param>
        /// <returns></returns>
        public override async Task OnDisconnectedAsync(Exception exception)
        {
            var ConnectionId = Context.ConnectionId;
            userIds.TryRemove(ConnectionId, out string outs);
            await Groups.RemoveFromGroupAsync(Context.ConnectionId, "SignalR Users");
            await base.OnDisconnectedAsync(exception);
        }


    }
}

4.注册服务

 

 

 

 

获取到js的客户端文件

cdn 

 <script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/3.1.7/signalr.min.js"></script>

 

 

 

 

 客户端输入以下js

"use strict";

var connection = new signalR.HubConnectionBuilder().withUrl("/signalRHub").build();

//Disable send button until connection is established
document.getElementById("sendButton").disabled = true;

connection.on("ReceiveMessage", function (user, message) {
    console.log(user)
    var msg = message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
    var encodedMsg = user + " says " + msg;
    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("SendMessageToUser", user, message).catch(function (err) {
        return console.error(err.toString());
    });
    event.preventDefault();
});

效果图

 

 

以上是关于web api使用SignalR的主要内容,如果未能解决你的问题,请参考以下文章

支持 https 的 Owin 自托管控制台应用程序(无 Web api,无 SignalR)

如何使用Owin和Web Api 2在SignalR上配置MessagePack?

带有 Web API 延迟的 Android 推送通知和 SignalR 通知

将 .net 远程处理替换为 WEB API、WCF、SignalR 或 Akka.net

SignalR 与 Service Fabric 无状态 Web API

Azure 移动服务 Web Api 上的 SignalR CORS