小程序 connectSocket使用
// 小程序connectSocket连接初始化
async startConnect() {
// 本地测试使用 ws协议 ,正式上线使用 wss 协议, 此地址为后端规定,可在其后面直接拼接参数
// 例如: ws://192.168.0.1:8080?member_id=45&schedule_id=1&nickname=777
let url = 'ws://192.168.0.1:8080';
// 创建实例
this.wxst = wx.connectSocket({
url: url,
method: "GET"
});
// 连接成功回调
this.wxst.onOpen(res => {
console.log('连接打开成功');
});
// 连接失败回调
this.wxst.onError(res => {
console.log('连接失败:', res);
});
// 服务端返回信息
this.wxst.onMessage(res => {
console.log('服务端返回信息:', res);
});
// 连接关闭回调
this.wxst.onClose(() => {
console.log('连接关闭啦');
// 连接断开重连
this.startConnect();
});
},
在onload中调用 startConnect()
方法,然后在不同的回调中处理相关数据即可.