服务器端引入包 npm install @aspnet/signalr
![]()
1 <template>
2 <div><p>测试SignalR后台推送消息</p><p>ConnectionId {{connectId}}</p> {{retData}}</div>
3 </template>
4
5 <script>
6 import * as signalR from '@aspnet/signalr'
7 export default {
8 data() {
9 return {
10 retData: '',
11 connection: "",
12 connectId:""
13 }
14 },
15 methods: {
16 },
17 created: function () {
18 let thisVue = this;
19
20 //1 客户端创建连接
21 let connection = new signalR.HubConnectionBuilder()
22 .withUrl('/api/chathub')
23 //.withUrl('/chathub',signalR.HttpTransportType.WebSockets)//手动指定传输方式, 请在withUrl()方法的第二个参数
24 .build();
25
26 //2 监听服务器端发送的方法
27 connection.on('someFunc', function (obj) {
28 thisVue.retData =obj.radom ;
29 });
30 connection.on('receiveupdate', function (obj) {
31 thisVue.retData =obj ;
32 });
33 connection.on('getconnectId', function (obj) {
34 thisVue.connectId = obj.connectId
35 });
36 connection.on('finsied', function () {
37 connection.stop();
38 thisVue.retData = "finished"
39 });
40
41 //3 开始通信,并调用服务器端方法GetLatestCount
42 connection.start()
43 //.then(() => {connection.invoke('GetLatestCount', 1);thisVue.retData = "started"})
44 .catch(err => console.error(err.toString()));
45 }
46 }
47 </script>
前端代码