1、前言在看文章之前,首先提2個問題:WebSocket 是什么原理?為什么可以實現持久連接?如果你不甚了解,請點擊傳送門2、概述websocket是一種全新的協議,不屬于http無狀態協議,協議 ...
在看文章之前,首先提2個問題:
websocket是一種全新的協議,不屬于http無狀態協議,協議名為"ws",這意味著一個websocket連接地址會是這樣的寫法:ws://**。websocket協議本質上是一個基于tcp的協議。
<!--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">發送</button>
</view>
</view>
上面代碼中:
連接socket 按鈕綁定 socketBtnTap()
發送按鈕 綁定 sendMessageBtnTap()
<!--index.js-->
//獲取應用實例
var app = getApp()
var socketOpen = false
var socketMsgQueue = []
Page({
data: {
userInfo: {},
socktBtnTitle: '連接socket'
},
socketBtnTap: function () {
var that = this
var remindTitle = socketOpen ? '正在關閉' : '正在連接'
wx.showToast({
title: remindTitle,
icon: 'loading',
duration: 10000
})
if (!socketOpen) {
//創建一個 WebSocket 連接;
//一個微信小程序同時只能有一個 WebSocket 連接,如果當前已存在一個 WebSocket 連接,會自動關閉該連接,并重新創建一個 WebSocket 連接。
wx.connectSocket({
url: 'ws://域名'
})
//監聽WebSocket錯誤
wx.onSocketError(function (res) {
socketOpen = false
console.log('WebSocket連接打開失敗,請檢查!')
that.setData({
socktBtnTitle: '連接socket'
})
wx.hideToast()
})
//監聽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 = []
})
//監聽WebSocket接受到服務器的消息事件
wx.onSocketMessage(function (res) {
console.log('收到服務器內容:' + res.data)
})
//監聽WebSocket關閉
wx.onSocketClose(function (res) {
socketOpen = false
console.log('WebSocket 已關閉!')
wx.hideToast()
that.setData({
socktBtnTitle: '連接socket'
})
})
} else {
//關閉WebSocket連接。
wx.closeSocket()
}
},
//事件處理函數
bindViewTap: function () {
wx.navigateTo({
url: '../logs/logs'
})
},
sendSocketMessage: function (msg) {
if (socketOpen) {
//通過 WebSocket 連接發送數據,需要先 wx.connectSocket,并在 wx.onSocketOpen 回調之后才能發送。
wx.sendSocketMessage({
data: msg
})
} else {
socketMsgQueue.push(msg)
}
},
sendMessageBtnTap: function () {
this.sendSocketMessage('小程序來了')
},
onLoad: function () {
console.log('onLoad')
var that = this
//調用應用實例的方法獲取全局數據
app.getUserInfo(function (userInfo) {
//更新數據
that.setData({
userInfo: userInfo
})
})
}
})
node.js服務器的實現使用了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)
//發生錯誤
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');
});
//發送消息
ws.send('something');
});