webSocket关闭后重连,无法发送消息。
发布于 5 年前 作者 taoyan 10949 次浏览 来自 问答

代码如下:

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

})

};

回到顶部