uni-app 中使用signalR 同时支持H5端和APP,小程序端不支持
注:推荐使用uniapp websocket原生链接signalR uniapp 原生websocket 使用 signalr - 落叶子 - 博客园 (cnblogs.com)
App端只测试了Android,ios没测试,有条件的可以测试下,测试最好能把结果告知我下,多谢
主要使用了renderjs,先在项目根目录安装signalR
npm i @microsoft/signalr
页面中的写法
<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>