微信小程序websocket实例
效果展示
wxml
<button bindtap="webSocket">connect</button>
<rich-text>{{html}}</rich-text>
js
下面是js中除了生命周期函数之外的部分
var socketQueue = ["ready","to","send"];
function sendSocketMessage(msg) {
wx.sendSocketMessage({
data: msg,
})
}
Page({
/**
* 页面的初始数据
*/
data: {
html:\'\'
},
webSocket: function () {
//这里需要用that记录一下对象,否则下面用this操作的对象就不对了
var that=this;
//建立连接
wx.connectSocket({
url: \'ws://49.234.18.41:8866\',
header: {
"content-type": "application/json"
}
})
//监听打开
wx.onSocketOpen((result) => {
console.log("webSocket已打开");
for (let i = 0; i < socketQueue.length; i++) {
//发送数据
sendSocketMessage(socketQueue[i]);
}
socketQueue = [];
//清空数组
})
//监控失败操作
wx.onSocketError((result) => {
console.log("webSocket打开失败");
})
//监听服务器返回的数据
wx.onSocketMessage((result) => {
console.log("收到服务器内容:"+result.data);
that.setData({
html:result.data
});
})
},
})
请发表评论