uniapp中使用websocket,后端为http,非ws
2021-02-23 本文已影响0人
前端小飞象
在uniapp中接入 SockJS
,Stomp
后,H5正常,打包App后报错
原因是APP不支持SockJS,但是由于业务需求,后端是https,不能改成wss。采用了WebView解决了这个问题。将webSockt写在html里,然后将html运行在vue中,但是zIndex层级写低点,置于底层。再像vue页面通讯即可
- 问题,不能在view直接声明webView,因为在app端无法隐藏webview
https://uniapp.dcloud.io/component/web-view web-view 中的
webview-styles
属性也只支持progress,写其他的没有作用
<view style="z-index: -1000;visibility: hidden;">
<web-view @message="socketInfo" src="/hybrid/html/local.html"></web-view>
</view>
- 因此使用了plus的api,实现如下(需要socket的vue文件)
var wv = plus.webview.create('/hybrid/html/local.html', '1', { zindex: 0, width: '0px', height: '0px' } });
var currentWebview = _this.$scope.$getAppWebview();
currentWebview.append(wv);
//重点: 监听子页面uni.postMessage返回的值
plus.globalEvent.addEventListener('plusMessage', function(msg) {
if (msg.data.args.data.name == 'postMessage') {
_this.msg = JSON.stringify(msg.data.args.data.arg);
// console.log('子页面返回的数据为:' + JSON.stringify(msg.data.args.data.arg));
}
});
- html内实现
如果vue页面需要向html传参,可以使用localStorage,vue页面设置
uni.setStorageSync('ids', i.ids);
,html页面plus.storage.getItem('ids')获取
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<div id="btn" style="margin-top:100px;color: #007AFF;">
123123
</div>
</body>
<!-- html中可以使用uniapp的部分api,查看文档 https://uniapp.dcloud.io/component/web-view -->
<script type="text/javascript" src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js"></script>
<script src="./socket/sockjs.min.js" type="text/javascript" charset="utf-8"></script>
<script src="./socket/stomp.js" type="text/javascript" charset="utf-8"></script>
<script style="text/javascript">
document.addEventListener('UniAppJSBridgeReady', function() {
console.log("加载完成,可以使用uni相关接口");
let socket = new SockJS('http://xx.xxx');
var socketTask = Stomp.over(socket);
socketTask.heartbeat.outgoing = 50000;
socketTask.heartbeat.incoming = 0;
socketTask.connect({}, (frame) => {
console.log("连接成功");
socketTask.subscribe('/stock/'+JSON.parse(plus.storage.getItem('userId')).data, response => {
var wsData = JSON.parse(response.body);
// 向vue页面推送信息
uni.postMessage({
data: {
index:'second',
second: wsData
}
})
});
})
});
</script>
</html>