1赔退、前言
在看文章之前,首先提2個(gè)問題:
- WebSocket 是什么原理创译?
- 為什么可以實(shí)現(xiàn)持久連接残制?
如果你不甚了解颗祝,請點(diǎn)擊傳送門
2、概述
websocket是一種全新的協(xié)議,不屬于http無狀態(tài)協(xié)議凤藏,協(xié)議名為"ws"欠雌,這意味著一個(gè)websocket連接地址會(huì)是這樣的寫法:ws://**禁炒。websocket協(xié)議本質(zhì)上是一個(gè)基于tcp的協(xié)議。
3涯捻、小程序具體實(shí)現(xiàn)
<!--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)用實(shí)例
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)建一個(gè) WebSocket 連接蝗拿;
//一個(gè)微信小程序同時(shí)只能有一個(gè) WebSocket 連接,如果當(dāng)前已存在一個(gè) WebSocket 連接仓手,會(huì)自動(dòng)關(guān)閉該連接补履,并重新創(chuàng)建一個(gè) WebSocket 連接贬蛙。
wx.connectSocket({
url: 'ws://域名'
})
//監(jiān)聽WebSocket錯(cuò)誤
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)用實(shí)例的方法獲取全局?jǐn)?shù)據(jù)
app.getUserInfo(function (userInfo) {
//更新數(shù)據(jù)
that.setData({
userInfo: userInfo
})
})
}
})
4剂邮、node.js服務(wù)器具體實(shí)現(xiàn)
node.js服務(wù)器的實(shí)現(xiàn)使用了ws
- 安裝ws
npm install --save 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的一個(gè)實(shí)例
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ā)生錯(cuò)誤
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');
});
5、如何還不明白翼虫,怎么辦死陆?
- 請私信我或者下載源碼