代码如下:
Page({
/**
* 页面的初始数据
*/
data: {
socketOpen:false
},
onLoad: function (options) {
conWebsocket(this);
},
sendMessage:function(){
if (!this.data.socketOpen){
conWebsocket(this);
}
sendSocketMessage(“test!”);
}
});
var conWebsocket = function (that) {
wx.connectSocket({
url: ‘ws://test.***.com/chat’,
data: {
},
header: {
‘content-type’: ‘application/json’
},
method: “GET”
})
wx.onSocketOpen(function (res) {
console.log(‘WebSocket连接已打开!’)
that.data.socketOpen = true;
})
wx.onSocketMessage(function (res) {
console.log(‘收到服务器内容:’ + res.data)
})
wx.onSocketError(function (res) {
console.log(‘WebSocket连接打开失败,请检查!’)
})
wx.onSocketClose(function (res) {
console.log(‘WebSocket 已关闭!’);
that.data.socketOpen = false;
})
}
var sendSocketMessage = function(msg) {
wx.sendSocketMessage({
data: msg
})
};