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, "&").replace(/</g, "<").replace(/>/g, ">"); 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(); });
效果图