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');
});