1、前言在看文章之前,首先提2個問題:WebSocket 是什么原理?為什么可以實現(xiàn)持久連接?如果你不甚了解,請點擊傳送門2、概述websocket是一種全新的協(xié)議,不屬于http無狀態(tài)協(xié)議,協(xié)議 ...
在看文章之前,首先提2個問題:
websocket是一種全新的協(xié)議,不屬于http無狀態(tài)協(xié)議,協(xié)議名為"ws",這意味著一個websocket連接地址會是這樣的寫法:ws://**。websocket協(xié)議本質(zhì)上是一個基于tcp的協(xié)議。
<!--index.wxml-->
<view class="container">
<view bindtap="bindViewTap" class="userinfo">
<image class="userinfo-avatar" src="{{userInfo.avatarUrl}}" background-size="cover"></image>
<text class="userinfo-nickname">{{userInfo.nickName}}</text>
</view>
<view class="voice">
<button type="primary" size="default" hover-class="button-hover" class="button-voice-play" bindtap="socketBtnTap">{{socktBtnTitle}}</button>
<button type="primary" size="default" hover-class="button-hover" class="button-voice-play" bindtap="sendMessageBtnTap">發(fā)送</button>
</view>
</view>
上面代碼中:
連接socket 按鈕綁定 socketBtnTap()
發(fā)送按鈕 綁定 sendMessageBtnTap()
<!--index.js-->
//獲取應(yīng)用實例
var app = getApp()
var socketOpen = false
var socketMsgQueue = []
Page({
data: {
userInfo: {},
socktBtnTitle: '連接socket'
},
socketBtnTap: function () {
var that = this
var remindTitle = socketOpen ? '正在關(guān)閉' : '正在連接'
wx.showToast({
title: remindTitle,
icon: 'loading',
duration: 10000
})
if (!socketOpen) {
//創(chuàng)建一個 WebSocket 連接;
//一個微信小程序同時只能有一個 WebSocket 連接,如果當(dāng)前已存在一個 WebSocket 連接,會自動關(guān)閉該連接,并重新創(chuàng)建一個 WebSocket 連接。
wx.connectSocket({
url: 'ws://域名'
})
//監(jiān)聽WebSocket錯誤
wx.onSocketError(function (res) {
socketOpen = false
console.log('WebSocket連接打開失敗,請檢查!')
that.setData({
socktBtnTitle: '連接socket'
})
wx.hideToast()
})
//監(jiān)聽WebSocket連接打開事件。
wx.onSocketOpen(function (res) {
console.log('WebSocket連接已打開!')
wx.hideToast()
that.setData({
socktBtnTitle: '斷開socket'
})
socketOpen = true
for (var i = 0; i < socketMsgQueue.length; i++) {
that.sendSocketMessage(socketMsgQueue[i])
}
socketMsgQueue = []
})
//監(jiān)聽WebSocket接受到服務(wù)器的消息事件
wx.onSocketMessage(function (res) {
console.log('收到服務(wù)器內(nèi)容:' + res.data)
})
//監(jiān)聽WebSocket關(guān)閉
wx.onSocketClose(function (res) {
socketOpen = false
console.log('WebSocket 已關(guān)閉!')
wx.hideToast()
that.setData({
socktBtnTitle: '連接socket'
})
})
} else {
//關(guān)閉WebSocket連接。
wx.closeSocket()
}
},
//事件處理函數(shù)
bindViewTap: function () {
wx.navigateTo({
url: '../logs/logs'
})
},
sendSocketMessage: function (msg) {
if (socketOpen) {
//通過 WebSocket 連接發(fā)送數(shù)據(jù),需要先 wx.connectSocket,并在 wx.onSocketOpen 回調(diào)之后才能發(fā)送。
wx.sendSocketMessage({
data: msg
})
} else {
socketMsgQueue.push(msg)
}
},
sendMessageBtnTap: function () {
this.sendSocketMessage('小程序來了')
},
onLoad: function () {
console.log('onLoad')
var that = this
//調(diào)用應(yīng)用實例的方法獲取全局?jǐn)?shù)據(jù)
app.getUserInfo(function (userInfo) {
//更新數(shù)據(jù)
that.setData({
userInfo: userInfo
})
})
}
})
node.js服務(wù)器的實現(xiàn)使用了ws
<!-- koa2_webSocket/bin/www.js -->
const webSocket = require('ws');
/**
* Create WebSocket
*/
const wss = new webSocket.Server({server});
//const wss = new webSocket('wss://echo.websocket.org/', {
// origin: 'https://websocket.org'
//});
//握手完成 ws是WebSocket的一個實例
wss.on('connection', function connection(ws) {
console.log(ws.upgradeReq.url);
//const location = url.parse(ws.upgradeReq.url, true);
// You might use location.query.access_token to authenticate or share sessions
// or ws.upgradeReq.headers.cookie (see http://stackoverflow.com/a/16395220/151312)
//發(fā)生錯誤
ws.on('error', function incoming(message) {
console.log('error: %s', message);
});
//斷開連接
ws.on('close', function incoming(message) {
console.log('close: %s', message);
});
//收到消息
ws.on('message', function incoming(message) {
console.log('received: %s', message);
ws.send('something123');
});
//發(fā)送消息
ws.send('something');
});
工作日 8:30-12:00 14:30-18:00
周六及部分節(jié)假日提供值班服務(wù)