第一步:创建一个 WebSocket 连接
wx.connectSocket({
url: "wss://websocket.allhjs.com",
})
第二步:监听WebSocket连接打开
wx.onSocketOpen(res => {
this.setData({ socketOpen: true })
})
第三步: wx.onSocketOpen 回调之后发送消息
if (socketOpen) {
wx.sendSocketMessage({
data:msg
})
}
第四步:监听服务器返回的消息
wx.onSocketMessage(function(res) {
console.log('收到服务器内容:' + res.data)
})
第五步:由于同时只能有2个websocket,所以页面卸载要关闭websocket
onUnload:function(){
wx.closeSocket();
},
下面贴上项目中一个完整的代码
//发表评论
sendChat(){
if (!this.data.chatInfo){
util.showToast('评论内容不能为空','none');
return;
}
let params = {
meetingId: this.data.meetingId,
content: this.data.chatInfo
}
this.websocket(this.data.chatInfo,params);
},
//连接websocket
websocket(msg,params){
let socketOpen = this.data.socketOpen;
let obj = {
name: this.data.userInfo.nickName,
userId: this.data.userId,
meetingId: this.data.meetingId,
addTime: util.formatTime(new Date()),
content: msg
}
if (socketOpen){
wx.sendSocketMessage({
data: "{'userId':" + wx.getStorageSync('userId') + ",'databagId':" + this.data.meetingId + ",'msg':" + msg + ",'name':" + this.data.userInfo.nickName + "}",
success:r =>{
util.request(api.sendChats, params).then(r => {
this.setData({ chatInfo: '' })
})
},
fail:err =>{
util.showToast('服务器已断开','none')
wx.connectSocket({
url: "wss://websocket.allhjs.com?databagId=" + this.data.meetingId + "&userId=" + wx.getStorageSync('userId') + "&name=" + this.data.userInfo.nickName,
})
wx.onSocketOpen(res => {
this.setData({ socketOpen: true })
})
console.log('err',err)
}
})
}else{
util.showToast('通信错误,请返回重连','none')
}
},
onLoad: function(options) {
this.getActDeatil(options.id);
this.setData({ userId: wx.getStorageSync('userId'),userInfo: wx.getStorageSync('userInfo'), meetingId: options.id })
//建立websocket
wx.connectSocket({
url: "wss://websocket.allhjs.com?databagId=" + this.data.meetingId + "&userId=" + wx.getStorageSync('userId') + "&name=" + this.data.userInfo.nickName,
})
wx.onSocketOpen(res => {
this.setData({ socketOpen: true })
})
wx.onSocketError(res => {
console.log('WebSocket连接打开失败,请检查!')
})
wx.onSocketMessage(res => {
let chatList = this.data.chatList;
let obj = JSON.parse(res.data);
let params = {
addTime: util.formatTime(new Date()),
content: obj.msg,
name: obj.name,
userId: obj.userId
}
chatList.push(params);
this.setData({ chatList })
setTimeout(() => { this.setData({ toView: 'bottom' }) }, 1)
})
},
onUnload:function(){
wx.closeSocket();
}