简要记录uni-app中使用websocket进行通信
1. 初始化
定义全局变量webSocketTask: {}
onLoad()中使用uni.connectSocket建立websocket长链接
this.webSocketTask = uni.connectSocket({
url: common.wsUrl() + ':8082/websocket/' + this.userId,
success: () => {
console.info("-------connectSocket success--------")
},
fail: () => {
console.info("-------connectSocket fail--------")
},
complete: () => {
console.info("-------connectSocket complete--------")
}
});
监听WebSocket连接打开事件
this.webSocketTask.onOpen((res) => {
console.info("----webSocketTask---websocketOpen--------")
});
监听WebSocket错误
uni.onSocketError((res) => {
console.info("-------websocketerror--------" + res)
});
接收websocket消息及处理
this.webSocketTask.onMessage((res) => {
let wsData = JSON.parse(res.data);
console.info("------接收webSocketTask消息--------" + res.data)
});
2. 发送websocket消息
自定义json对象作为传递参数,接收时对应解析
const wsData = {
content: '',
type: '0'
}
this.webSocketTask.send({
data: JSON.stringify(wsData)
});
3. 关闭websocket
记得在需要时或离开页面时onUnload()关闭websocket
uni.closeSocket({
success: () => {
console.info("-------close websocket success--------")
},
fail: () => {
console.info("-------close websocket fail--------")
},
})