public class MyHub : Hub { private readonly IMemoryCache memoryCache; public MyHub(IMemoryCache memoryCache) { this.memoryCache = memoryCache; } public void CreateConnection(int userId) { // 堆代码 duidaima.com // 将用户标识与 ConnectionId 关联起来 memoryCache.Set(userId, Context.ConnectionId); } public async Task SendMessageToUser(int userId, string message) { if (memoryCache.TryGetValue(userId, out var connectionId)) { await Clients.Client(connectionId.ToString()).SendAsync("ReceiveMessage", message); } } }在program文件中注册hub
//注册signalr builder.Services.AddSignalR(); //注册hub 这里的路径是我的Hub类在项目中的路径 app.MapHub<MyHub>("/SignalR/MyHub");让后前端这里在vue项目中下载@microsoft/signalr包
npm i @microsoft/signalr --save创建一个myHub.js文件
import * as signalr from '@microsoft/signalr'; const conn = new signalr.HubConnectionBuilder() .withUrl('http://localhost:5124/SignalR/Myhub') .withAutomaticReconnect() .build(); export default conn;withUrl('http://localhost:5124/SignalR/Myhub')这里的路径一定要和在api项目中的Program配置的app.MapHub("/Signalr/Myhub");相同。withAutomaticReconnect()用于启用自动重连功能。这意味着如果连接断开,SignalR将自动尝试重新建立连接,以确保保持实时通信。.build()方法构建并返回一个SignalR连接对象。conn.start();和SignarlR启动建立连接。
[Route("api/[controller]/[action]"), ApiController] public class TestController : ControllerBase { List<SysUser> userList = new List<SysUser>() { new SysUser(1,"王鹤棣","123456"), new SysUser(2,"吴磊","123456"), new SysUser(3,"赵露思","123456") }; [HttpPost] public ActionResult Login(SysUser sysUser) { var user = userList.Where(s => s.userName == sysUser.userName && s.userPwd == sysUser.userPwd).FirstOrDefault(); if (user is not null) { return Ok(user.userId); } return Ok("失败"); } } public record SysUser(int? userId,string userName,string userPwd);Vue部分
<script setup> import {ref,reactive,onMounted} from 'vue'; import axios from 'axios'; import myHub from './httpTools/myHub'; //导入hub const loginUser=reactive({ userName:'王鹤棣', userPwd:'123456', }); const loginBtn= ()=>{ axios.post('http://localhost:5159/api/test/login',loginUser) .then(async res => { console.log(res); alert('成功'); //这里在登录成功之后调用服务端在MyHub类的CreateConnection方法, //把登录成功之后返回的userId传过去 //使客户端与服务端建立连接 if(myHub.state.toString()!="Connected"){ await myHub.start(); } myHub.invoke("CreateConnection",res.data); }) } //这里的ReceiveMessage用于接受服务器发送的消息 //这个ReceiveMessage名字是自己定义的 onMounted(() => { myHub.on('ReceiveMessage', (message) => { console.log("MyHub接受到的消息:"+message); alert(message); }) }) const message=ref(); const sendUserId=ref(); const sendMessage=()=>{ myHub.invoke("SendMessageToUser",Number(sendUserId.value),message.value) } </script> <template> <input type="text" v-model.trim="loginUser.userName" placeholder="用户名"> <input type="text" v-model.trim="loginUser.userPwd" placeholder="密码"> <button @click="loginBtn">确定</button> <input type="text" v-model="message"> <select v-model="sendUserId"> <option value="1">王鹤棣</option> <option value="2">吴磊</option> <option value="3">赵露思</option> </select > <button @click="sendMessage">发送消息</button> </template>
效果: