手把手教你玩轉小程式websocket
阿新 • • 發佈:2019-01-29
第一步:建立一個 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();
}