1.请求地址必须是ws://或wss://
var?wsurl?=?'wss://zsj.itdos.net/v1'
2.服务端websocket必须返回文件头protocol
小程序端请求会发送protocol,服务端必须取得这个再发回去?
go语言这样处理:https://studygolang.com/articles/22255?fr=sidebar
websocket包采用的是github.com/gorilla/websocket
var upgrade = websocket.Upgrader{
// cross origin domain
CheckOrigin: func(r *http.Request) bool { //这个是解决跨域问题
return true
},
Subprotocols:[]string{s.Ctx.Input.Header("Sec-WebSocket-Protocol")},
//将获取的参数放进这个数组,问题解决
}
3.小程序wss请求带上sessionid,才能进行用户判断
?https://blog.csdn.net/zhangheng028/article/details/50352564
4.上小程序代码
// 计算
formSubmit: function (e) {
var that = this;
if (that.data.NumberError != null) {
wx.showToast({
title: "输入存在错误",
icon: 'none',
duration: 2000
});
return;
}
//清除计时器 即清除setInter
clearInterval(that.data.setInter)
that.setData({
canDownload: false,
num: 0,
canCalculate: false
})
//将计时器赋值给setInter
that.data.setInter = setInterval(
function () {
var numVal = that.data.num + 1;
that.setData({
num: numVal
});
}, 1000);
var sessionId = wx.getStorageSync('sessionId')
var apiUrl = config.wsurl + '/mathcad/postwxmath2/' + that.data.id+'?hotqinsessionid='+sessionId;
var obj = {};
obj.message = new Date().toLocaleString();
obj.templeid = that.data.id
obj.inputdata = e.detail.value
obj = JSON.stringify(obj); //将JSON对象转化为JSON字符
let SocketTask = wx.connectSocket({
url: apiUrl, //'wss://example.qq.com',
header: {
'content-type': 'application/json'
},
protocols: ['protocol1'],
method: "GET",
success: function (res) {
console.log(res)
}
})
SocketTask.onOpen(function (res) {
// console.log('WebSocket连接已打开!')
SocketTask.send({
data: obj, //postData,
success: function () {
console.log('发送成功')
// console.log(obj)
},
fail: function (err) {
console.log('发送失败')
console.log(err)
// 停止计时器
clearInterval(that.data.setInter)
}
})
})
SocketTask.onClose(function (res) {
console.log('WebSocket连接已关闭!')
})
SocketTask.onMessage(function (res) {
// console.log('接收到的消息:' + res.data)
var msg = JSON.parse(res.data);
var tmpArr = that.data.wsMessage + msg.message + '\n';
that.setData({
wsMessage: tmpArr
})
if (msg.info == "ERROR") {
//清除计时器 即清除setInter
clearInterval(that.data.setInter)
that.setData({
canCalculate: true
})
wx.showToast({
title: msg.data.info,
icon: 'none',
duration: 2000
})
} else if (msg.info == "SUCCESS") {
// 停止计时器
clearInterval(that.data.setInter)
that.setData({
mathcaloutput: msg.data,
canDownload: true,
canCalculate: true,
pdflink: msg.pdflink
})
}
})
},
|