微信小程序客户端与服务端进行WebSocket通信
(一)首先去nginx配置websocket的通信协议
(二)然后编写wx.js代码
Page({
data: {
socketStatus: 'closed',
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
var that = this;
if (that.data.socketStatus === 'closed') {
that.openSocket();
}
},
openSocket:function() {
//打开时的动作
wx.onSocketOpen(() => {
console.log('WebSocket 已连接')
this.data.socketStatus = 'connected';
this.sendMessage();
})
//断开时的动作
wx.onSocketClose(() => {
console.log('WebSocket 已断开')
this.data