封装小程序的websocket
这两天的工作中,我重构了一个项目里的客服聊天功能,是小程序的,用了小程序提供的websocket有关的接口,我感觉很简单,和web端的接口大体一致,不过我喜欢封装后去使用,封装成一个类,创建一个类的实例,通过这个实例上的方法去调用方法,去监听返回的消息,同时发送消息,我觉得这样会比较方便。
/**
* 返回一个布尔值判断传入的url是否为WSS开头的链接
* @param {String} url 需要判断的URL
*/
function isAbsoluteWss(url) {
return /^(wss:\/\/).*/.test(url)
}
export default class Socket {
/** 链接的URL */
url = ''
/** 是否链接成功的状态 */
socketOpenStatus = false
/** 实例 */
websocket = null
/** 消息队列 */
socketMsgQueue = []
/** 消息监听的函数 */
fn = null
/**
*
* @param {String} url websocket的链接地址
* @param {Function} fn 消息监听事件
*/
constructor(url, fn) {
if (!url)
throw new Error('websocket的链接URL不能为空')
if (!isAbsoluteWss(url))
throw new Error(`websocket的链接${url}必须是以 wss:// 开头`)
this.url = url
this.fn = fn
}
/** 链接websocket */
connect() {
this.websocket = wx.connectSocket({
url: this.url
})
// 监听websocket链接打开
this.websocket.onOpen((data) => {
this.socketOpenStatus = true
// 初始化监听事件
this.initHandleMonitor()
if (this.fn) {
this.fn({
type: 'open',
data
})
}
// 如果消息队列里有消息
if (this.socketMsgQueue.length) {
this.socketMsgQueue.forEach(item => item())
}
this.socketMsgQueue = []
})
}
/** 发送消息 */
send(data) {
if (data !== null && typeof data === 'object') {
data = JSON.stringify(data)
}
// 判断当前的链接是否链接成功
if (this.socketOpenStatus) {
this.websocket.send({
data
})
} else {
this.socketMsgQueue.push(() => {
this.websocket.send({
data
})
})
}
}
/** 监听消息的绑定 */
initHandleMonitor() {
/** 消息的回调 */
this.websocket.onMessage(res => {
const data = JSON.parse(res.data)
if (this.fn) {
this.fn({
type: 'message',
data
})
}
})
/** 报错的回调 */
this.websocket.onError(res => {
this.socketOpenStatus = false
if (this.fn) {
this.fn({
type: 'error',
data: res.errMsg
})
}
})
/** 关闭的回调 */
this.websocket.onClose(data => {
this.socketOpenStatus = false
if (this.fn) {
this.fn({
type: 'close',
data
})
}
})
}
/** 关闭websocket链接 */
close(code, reason) {
if (this.socketOpenStatus) {
this.socketOpenStatus = false
this.websocket.close({
code,
reason
})
}
}
/** 返回是否链接成功 */
isOpen() {
return this.socketOpenStatus
}
}本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!