Commit e4f256da by liang ce

socket封装

parent 12b6f5a9
......@@ -14,7 +14,7 @@ App({
},
globalData: {
loadingType: 0,
// globalUrl: 'http://192.167.1.101:9999'
// globalUrl: 'http://192.168.1.101:9999'
globalUrl: 'https://gateway.mingwork.com'
}
});
......@@ -45,7 +45,6 @@ Page({
getUserMsg(code) {
const _that = this;
let orgId = dd.corpId;
dd.httpRequest({
headers: {
"Content-Type": "application/x-www-form-urlencoded"
......
......@@ -11,7 +11,7 @@
</view>
<view class="balanceBox">
<view class="balancetitle">账户余额</view>
<view>¥ <view class="balanceNum">{{realityBalance || '--'}}</view></view>
<view>¥ <view class="balanceNum">{{name ? realityBalance.toFixed(2) : '--'}}</view></view>
</view>
<view class="indexItemList">
<view touchStart="touchStyle" touchEnd="touchEnd" onTap="toPayment"><image mode="scaleToFill" src="./../../assets/QRcode.png"/>付款</view>
......
......@@ -2,6 +2,7 @@ var app = getApp()
import QR from '../../utils/QRcode';
import $http from '../../API/http';
const aes = require('./../../utils/aeskey.js');
const webSocket = require('./../../utils/socket.js');
let timeRefreshQRcode = '';
Page({
data: {
......@@ -138,28 +139,28 @@ Page({
_that.refreshQRcode();
}, 55000);
},500)
console.log(dd.corpId,'dd.corpId')
//页面显示
dd.connectSocket({
url: `wss://gateway.mingwork.com/mingpay-phone/v1/mingpaywebsocket?param=${dd.corpId}_${dd.getStorageSync({ key: 'userId' }).data}`,
});
dd.onSocketOpen(function(res) {
console.log('WebSocket 连接已打开!');
dd.getNetworkType({
success: (res) => {
// 有网络状态
if (res.networkAvailable) {
// 获取免登授权码
webSocket.connectSocket();
webSocket.onSocketMessageCallback = this.onSocketMessageCallback;
}
}
});
dd.onSocketError(function(res){
},
// socket收到的信息回调
onSocketMessageCallback: function(res) {
if (res === 'isHeart!!') {
console.log(res)
console.log('WebSocket 连接打开失败,请检查!');
});
dd.onSocketClose(function(res) {
console.log('WebSocket 已关闭!')
})
dd.onSocketMessage(function(res) {
let resData = JSON.parse(res.data)
} else {
let resData = JSON.parse(res)
console.log(resData)
if(resData.paymentCode === 0){
// dd.closeSocket();
dd.navigateTo({
url: `./../paySuccess/paySuccess?money=${(JSON.parse(res.data).orderAmount.toFixed(2))}`
url: `./../paySuccess/paySuccess?money=${(resData.orderAmount.toFixed(2))}`
})
}else if(resData.paymentCode === 10001){
dd.alert({
......@@ -182,8 +183,7 @@ Page({
buttonText: '确定'
});
}
})
}
},
onHide() {
// 页面隐藏
......@@ -194,7 +194,8 @@ Page({
console.log('onUnload')
const _that = this;
clearInterval(timeRefreshQRcode);
dd.closeSocket();
webSocket.closeSocket();
// dd.closeSocket();
// dd.offSocketMessage()
},
......
// socket已经连接成功
var socketOpen = false
// socket已经调用关闭function
var socketClose = false
// socket发送的消息队列
var socketMsgQueue = []
// 判断心跳变量
var heart = ''
// 心跳失败次数
var heartBeatFailCount = 0
// 终止心跳
var heartBeatTimeOut = null;
// 终止重新连接
var connectSocketTimeOut = null;
var webSocket = {
/**
* 创建一个 WebSocket 连接
* @param {options}
* url String 是 开发者服务器接口地址,必须是 wss 协议,且域名必须是后台配置的合法域名
* header Object 否 HTTP Header , header 中不能设置 Referer
* method String 否 默认是GET,有效值:OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
* protocols StringArray 否 子协议数组 1.4.0
* success Function 否 接口调用成功的回调函数
* fail Function 否 接口调用失败的回调函数
* complete Function 否 接口调用结束的回调函数(调用成功、失败都会执行)
*/
connectSocket: function(options) {
dd.showLoading({
title: '',
mask: true,
})
socketOpen = false
socketClose = false
socketMsgQueue = []
dd.connectSocket({
url: `wss://mingpay-websocket.mingwork.com/v1/mingpaywebsocket?param=${dd.corpId}_${dd.getStorageSync({ key: 'userId' }).data}`,
data: {},
header:{
'content-type': 'application/json'
},
method:"GET",
success: function(res) {
console.log(res, `wss://gateway.mingwork.com/mingpay-phone/v1/mingpaywebsocket?param=${dd.corpId}_${dd.getStorageSync({ key: 'userId' }).data}`)
if (options) {
// 成功回调
options.success && options.success(res);
}
},
fail: function(res) {
console.log(res)
if (options) {
// 失败回调
options.fail && options.fail(res);
}
}
})
},
/**
* 通过 WebSocket 连接发送数据
* @param {options}
* data String / ArrayBuffer 是 需要发送的内容
* success Function 否 接口调用成功的回调函数
* fail Function 否 接口调用失败的回调函数
* complete Function 否 接口调用结束的回调函数(调用成功、失败都会执行)
*/
sendSocketMessage: function(options) {
if (socketOpen) {
dd.sendSocketMessage({
data: options.msg,
success: function(res) {
if (options) {
options.success && options.success(res);
}
},
fail: function(res) {
if (options) {
options.fail && options.fail(res);
}
}
})
} else {
socketMsgQueue.push(options.msg)
}
},
/**
* 关闭 WebSocket 连接。
* @param {options}
* code Number 否 一个数字值表示关闭连接的状态号,表示连接被关闭的原因。如果这个参数没有被指定,默认的取值是1000 (表示正常连接关闭)
* reason String 否 一个可读的字符串,表示连接被关闭的原因。这个字符串必须是不长于123字节的UTF-8 文本(不是字符)
* fail Function 否 接口调用失败的回调函数
* complete Function 否 接口调用结束的回调函数(调用成功、失败都会执行)
*/
closeSocket: function(options) {
if (connectSocketTimeOut) {
clearTimeout(connectSocketTimeOut);
connectSocketTimeOut = null;
}
socketClose = true;
var self = this;
self.stopHeartBeat();
dd.closeSocket({
success: function(res) {
console.log('WebSocket 已关闭!');
if (options) {
options.success && options.success(res);
}
},
fail: function(res) {
if (options) {
options.fail && options.fail(res);
}
}
})
},
// 收到消息回调
onSocketMessageCallback: function(msg) {
},
// 开始心跳
startHeartBeat: function() {
console.log('socket开始心跳')
var self = this;
heart = 'heart';
self.heartBeat();
},
// 结束心跳
stopHeartBeat: function() {
console.log('socket结束心跳')
var self = this;
heart = '';
if (heartBeatTimeOut) {
clearTimeout(heartBeatTimeOut);
heartBeatTimeOut = null;
}
if (connectSocketTimeOut) {
clearTimeout(connectSocketTimeOut);
connectSocketTimeOut = null;
}
},
// 心跳
heartBeat: function() {
var self = this;
if (!heart) {
return;
}
self.sendSocketMessage({
msg: JSON.stringify({
'msg_type': 'heart'
}),
success: function(res) {
console.log('socket心跳成功');
if (heart) {
heartBeatTimeOut = setTimeout(() => {
self.heartBeat();
}, 7000);
}
},
fail: function(res) {
console.log('socket心跳失败');
if (heartBeatFailCount > 2) {
// 重连
self.connectSocket();
}
if (heart) {
heartBeatTimeOut = setTimeout(() => {
self.heartBeat();
}, 7000);
}
heartBeatFailCount++;
},
});
}
}
// 监听WebSocket连接打开事件。callback 回调函数
dd.onSocketOpen(function(res) {
console.log('WebSocket连接已打开!')
dd.hideLoading();
// 如果已经调用过关闭function
if (socketClose) {
webSocket.closeSocket();
} else {
socketOpen = true
for (var i = 0; i < socketMsgQueue.length; i++) {
webSocket.sendSocketMessage(socketMsgQueue[i])
}
socketMsgQueue = []
webSocket.startHeartBeat();
}
})
// 监听WebSocket错误。
dd.onSocketError(function(res) {
console.log('WebSocket连接打开失败,请检查!', res)
})
// 监听WebSocket接受到服务器的消息事件。
dd.onSocketMessage(function(res) {
console.log('收到服务器内容:' + res.data)
webSocket.onSocketMessageCallback(res.data)
})
// 监听WebSocket关闭。
dd.onSocketClose(function(res) {
console.log('WebSocket 已关闭!')
if (!socketClose) {
clearTimeout(connectSocketTimeOut)
connectSocketTimeOut = setTimeout(() => {
webSocket.connectSocket();
}, 3000);
}
})
module.exports = webSocket
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment