小程序
小游戏
企业微信
微信支付
扫描小程序码分享
wx.connectSocket是异步的,那么如何获取SocketTask?以及如何用SocketTask监听?
现在文档给的都是分散的,希望官方一共一个完整的例子。
现在弄得一头雾水。
3 个回答
加粗
标红
插入代码
插入链接
插入图片
上传视频
1、socket.js 文件
import config from '@config'
const host = config.wsHOST
export default class WebSocket {
constructor({ heartBeat, roomId, onMessage }) {
// 是否已连接
this.connected = false
// 当前网络状态
this.netWorkState = true
// 心跳检测频率
this.timeout = 15000
// 计时器ID
this.timer = null
// 当前重连次数
this.connectNum = 0
// 心跳检测和断线重连开关
this.heartBeat = heartBeat
// 房间id
this.roomId = roomId
// 回调监听
this.message = onMessage
// socketTask
this.socketTask = null
// 初始化
this.initWebSocket()
}
/**
* 建立websocket连接
* @param {*} options
*/
initWebSocket(options) {
const that = this
if (this.connected) {
console.log("socket已连接")
} else {
// 检查网络
wx.getNetworkType({
success(net) {
if (net.networkType != 'none') {
const appId = that.appId()
that.socketTask = wx.connectSocket({
url: `${host}${that.roomId}/${appId}`,
success(res) {
console.log('socket连接成功', res)
// 已连接
that.connected = true
},
fail(err) {
console.log('socket连接失败', err)
})
// 监听 WebSocket 连接打开事件
that.onSocketOpened()
// 监听 WebSocket 连接关闭事件
that.onSocketClosed()
// 监听websocket 错误
that.onSocketError()
// 存在发生数据则需要发送数据
if (options) {
that.sendWebSocketMsg(options)
that.netWorkState = false
你好,麻烦通过点击下方“反馈信息”按钮,提供出现问题的。
webSocketInit () { const vm = this let token = '' let socketUrl = 'wss://websocket.test' // 建立 WebSocket 连接 vm.socket = wx.connectSocket({ url: socketUrl, header: { 'content-type': 'application/json', 'authorization': 'Bearer' + token, 'x-wxapp-sockettype': 'ordertips' }, success (res) { console.log('WebSocket 连接成功: ', res) }, fail (err) { console.log('WebSocket 连接失败: ', err) } }) // onOpen vm.socket.onOpen((ret) => { console.log('打开 WebSocket 连接') }) // onMessage vm.socket.onMessage((ret) => { if (ret.data == 'pong') { return; } let data = JSON.parse(ret.data) wx.showToast({ title: data.message, icon: 'none', duration: 3000 }) }) // onError vm.socket.onError((err) => { console.log('WebSocket 连接失败:', err) }) // onClose vm.socket.onClose((ret) => { console.log('断开 WebSocket 连接', ret) }) }, // send message send (msg) { const vm = this vm.socket.send({ data: msg, success (res) { console.log('WebSocket 消息发送成功', res) }, fail (err) { console.log('WebSocket 消息发送失败', err) } }) }, // 心跳,由客户端发起 ping () { const vm = this let times = 0 // 每 10 秒钟由客户端发送一次心跳 this.interval = setInterval(function () { if (vm.socket.readyState == 1) { vm.send('ping') } else if (vm.socket.readyState == 3) { times += 1 // 超时重连,最多尝试 10 次 if (times >= 10) { wx.showToast({ title: 'WebSocket 连接已断开~', icon: 'none', duration: 3000 }) clearInterval(vm.interval) } vm.reconnect() } }, 10000) }, // WebSocket 断线重连 reconnect () { const vm = this vm.webSocketInit() },
就是就是。 TCPSocket 还好多bug
关注后,可在微信内接收相应的重要提醒。
请使用微信扫描二维码关注 “微信开放社区” 公众号
1、socket.js 文件
import config from '@config'
const host = config.wsHOST
export default class WebSocket {
constructor({ heartBeat, roomId, onMessage }) {
// 是否已连接
this.connected = false
// 当前网络状态
this.netWorkState = true
// 心跳检测频率
this.timeout = 15000
// 计时器ID
this.timer = null
// 当前重连次数
this.connectNum = 0
// 心跳检测和断线重连开关
this.heartBeat = heartBeat
// 房间id
this.roomId = roomId
// 回调监听
this.message = onMessage
// socketTask
this.socketTask = null
// 初始化
this.initWebSocket()
}
/**
* 建立websocket连接
* @param {*} options
*/
initWebSocket(options) {
const that = this
if (this.connected) {
console.log("socket已连接")
} else {
// 检查网络
wx.getNetworkType({
success(net) {
if (net.networkType != 'none') {
const appId = that.appId()
that.socketTask = wx.connectSocket({
url: `${host}${that.roomId}/${appId}`,
success(res) {
console.log('socket连接成功', res)
// 已连接
that.connected = true
},
fail(err) {
console.log('socket连接失败', err)
}
})
// 监听 WebSocket 连接打开事件
that.onSocketOpened()
// 监听 WebSocket 连接关闭事件
that.onSocketClosed()
// 监听websocket 错误
that.onSocketError()
// 存在发生数据则需要发送数据
if (options) {
that.sendWebSocketMsg(options)
}
} else {
that.netWorkState = false
}
}
})
}
}
* WebSocket 错误事件的回调函数
*/
onSocketError() {
const that = this
that.socketTask.onError((errMsg) => {
console.log(errMsg)
})
}
/**
* 监听 WebSocket 连接打开事件
*/
onSocketOpened() {
const that = this
that.socketTask.onOpen(
(res) => {
console.log('socketTask.onOpen',res)
// 检查心跳
if (that.heartBeat) {
that.resetHeartBeat()
that.startHeartBeat()
}
that.sendTestMessage()
that.onReceivedMsg()
// 网络状态
that.netWorkState = true
}
)
}
/**
* 心跳检查重置
*/
resetHeartBeat() {
this.timer && clearTimeout(this.timer)
}
/**
* 心跳检查开始
*/
startHeartBeat() {
const that = this
that.timer = setInterval(() => {
that.sendTestMessage()
}, that.timeout)
}
/**
* 发送hearBeat测试信息
*/
sendTestMessage() {
const that = this
that.socketTask.send({
// 心跳发送的信息应由前后端商量后决定
data: 'HeartBeat',
success(res) {
console.log('发送测试信息成功', res)
},
fail(err) {
console.log('发送测试信息失败', err)
that.resetHeartBeat()
}
})
}
webSocketInit () { const vm = this let token = '' let socketUrl = 'wss://websocket.test' // 建立 WebSocket 连接 vm.socket = wx.connectSocket({ url: socketUrl, header: { 'content-type': 'application/json', 'authorization': 'Bearer' + token, 'x-wxapp-sockettype': 'ordertips' }, success (res) { console.log('WebSocket 连接成功: ', res) }, fail (err) { console.log('WebSocket 连接失败: ', err) } }) // onOpen vm.socket.onOpen((ret) => { console.log('打开 WebSocket 连接') }) // onMessage vm.socket.onMessage((ret) => { if (ret.data == 'pong') { return; } let data = JSON.parse(ret.data) wx.showToast({ title: data.message, icon: 'none', duration: 3000 }) }) // onError vm.socket.onError((err) => { console.log('WebSocket 连接失败:', err) }) // onClose vm.socket.onClose((ret) => { console.log('断开 WebSocket 连接', ret) }) }, // send message send (msg) { const vm = this vm.socket.send({ data: msg, success (res) { console.log('WebSocket 消息发送成功', res) }, fail (err) { console.log('WebSocket 消息发送失败', err) } }) }, // 心跳,由客户端发起 ping () { const vm = this let times = 0 // 每 10 秒钟由客户端发送一次心跳 this.interval = setInterval(function () { if (vm.socket.readyState == 1) { vm.send('ping') } else if (vm.socket.readyState == 3) { times += 1 // 超时重连,最多尝试 10 次 if (times >= 10) { wx.showToast({ title: 'WebSocket 连接已断开~', icon: 'none', duration: 3000 }) clearInterval(vm.interval) } vm.reconnect() } }, 10000) }, // WebSocket 断线重连 reconnect () { const vm = this vm.webSocketInit() },
{"errMsg":"closeSocket:fail WebSocket is not connected"}
就是就是。 TCPSocket 还好多bug