uniapp 原生websocket 使用 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
   //signalr得连接地址并携带token
let url = "ws://xxx/xxxHub"+ '?access_token=xxxx';
//开始连接
uni.connectSocket({
    url: url,
    method: 'GET',
    success: function() {}
});
//连接成功
uni.onSocketOpen(function(res) {<br>                        //告诉服务器使用 JSON 的形式进行消息的序列化
    uni.sendSocketMessage({
        data: `{"protocol":"json", "version":1}${String.fromCharCode(0x1e)}`
    });
    console.log('WebSocket连接已打开!');
 
});
//连接失败
uni.onSocketError(function(res) {
    console.log(res,'WebSocket连接打开失败,请检查!');
});
//接收到服务端消息
uni.onSocketMessage(function(res) {
    var msg = res.data.replace(String.fromCharCode(0x1e), ""); //替换消息结束符
    console.log("msg", msg)
    let msgData = JSON.parse(msg)
    //接收指定消息(这里为服务端得ReceiveMessage得消息,msgData.type === 1 为固定值表示调用客户端的一个方法)
    if (msgData.type === 1 && msgData.target == "ReceiveMessage") {
        console.log('收到服务器内容:' + JSON.stringify(msgData.arguments[0]));
    }
 
});
//断开时得方法
uni.onSocketClose(function(res) {
    console.log('WebSocket 已关闭!');
});
//执行服务端得方法 (methodName:方法名称,args:方法参数的值例如["张三","李四","王五"],type: 1 为固定值)
uni.sendSocketMessage({
    data: `${JSON.stringify({arguments: args,target: methodName,type: 1,})}${String.fromCharCode(0x1e)}`
});

  

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

相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!

导航

< 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
点击右上角即可分享
微信分享提示