需求:使用@microsoft/signalr进行前后端数据实时通讯(每秒)
环境:vue3 typescript @microsoft/signalr
安装:
npm install @microsoft/signalr
代码
<script lang="ts" setup> import {ref, reactive, computed,onMounted,watch , onUnmounted } from 'vue' import { HubConnectionBuilder } from '@microsoft/signalr'; import {Local, Session} from '/@/utils/storage'; // 缓存方法 const message = ref(''); // 用于显示从服务器接收的消息 const token = Session.get('token') const connection = new HubConnectionBuilder().withUrl("你的后端地址", { withCredentials: false,//不发送cookie accessTokenFactory: () => token // 登录token,用于辨别用户是谁 }).build(); const startConnection = () =>{ // 定义一个实例 connection.start().then(function () {// 开始连接 console.log('1 连接成功',connection) // 客户端与服务端进行沟通(客户端-->服务端),客户端调取后端的方法进行通讯,后端返回信息 connection.invoke("后端命名的方法A", "一些后端需要的变量根据自己需求填写").catch(function (err) { return console.log(err,'获取服务器方法失败'); }); }).catch(function (err) { return console.log('连接失败!!!',err); }); // 实时接收服务端信息(服务端-->客户端) connection.on('监听后端命名的方法A返回的数据:名称一般和上面invoke配套', (message) => { console.log('接受的信息Info message:', message); // 做一些赋值操作,把后端传来的数据渲染到页面 }); } // 在组件挂载时连接到 SignalR 服务器 onMounted(() => { startConnection() }) // 在组件卸载时断开连接 onUnmounted(() => { console.log('停止!!!!') connection.stop().catch((e) => console.error('停止失败-Failed to disconnect:', e)); }); </script>