uni-app 中使用signalR 同时支持H5端和APP,小程序端不支持

注:推荐使用uniapp websocket原生链接signalR   uniapp 原生websocket 使用 signalr - 落叶子 - 博客园 (cnblogs.com)

 

App端只测试了Android,ios没测试,有条件的可以测试下,测试最好能把结果告知我下,多谢 

主要使用了renderjs,先在项目根目录安装signalR

1
npm i @microsoft/signalr

页面中的写法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<template>
    <view class="content">
        <p>webscoket 是否链接:{{connected}}</p>
        <p>收到的消息:</p>
        <p>{{msg}}</p>
    </view>
</template>
<script>
export default {
    data() {
        return {
            title: 'Hello',
            connection: null,
            connected:false,
            msg:""
        };
    },
     
    methods: {
        isConnected(res){
            this.connected=res.connected;
        },
        revMsg(res){
            this.msg=res;
        }
    }
};
</script>
 
<script lang="renderjs" module="signalr">
    const signalR = require("@microsoft/signalr");
    export default {
        mounted(){
            // 建立连接
            this.connection =new signalR.HubConnectionBuilder()
                .withUrl("http://159.75.86.34:8082/chathub") // 此处填服务器地址
                .configureLogging(signalR.LogLevel.Information)
                .build();
             
            // 注册方法(给后端调用的,需要在methods中定义)
            this.connection.on("ReceiveMessage", this.ShowMsg);
            // 开始连接
            this.connection
                .start()
                .then((res) => {
                    console.log("Connected!a")
                    this.$ownerInstance.callMethod('isConnected', {connected: true})
                    this.connection.invoke("SendMessage", "hello world")
                })
                .catch((err) => {
                    console.log(err)
                });
        },
        methods: {
            ShowMsg(msgInfo) {
                this.$ownerInstance.callMethod('revMsg', msgInfo)
                console.log(msgInfo)
            }
        }
    }
</script>
 
<style>
    .content{
        padding-left: 20rpx;
    }
</style>

  

posted on   落叶子  阅读(3353)  评论(10编辑  收藏  举报

相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2018-04-28 IIS初始化(预加载),解决第一次访问慢,程序池被回收问题

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示