var socketOpen = false ; var frameBuffer_Data, session, SocketTask; var url = 'wss://...' ; Page({ data: { toView: 'green' , windowH: "1000" , user_input_text: '' , //用户输入文字 inputValue: '' , returnValue: '' , addImg: false , //格式示例数据,可为空 allContentList: [], num: 0, wo: "" , ta: "" , youImg: "" }, //通过 WebSocket 连接发送数据,需要先 wx.connectSocket,并在 wx.onSocketOpen 回调之后才能发送。 sendSocketMessage: function (msg) { var that = this ; console.log( '通过 WebSocket 连接发送数据' , JSON.stringify(msg)) // debugger SocketTask.send( { data: JSON.stringify(msg) }, function (res) { console.log( '已发送' , res) } ) }, onLoad: function (options) { const that = this ; }, onReady: function () { var that = this ; SocketTask.onOpen(res => { socketOpen = true ; console.log( '监听 WebSocket 连接打开事件。' , res) //发送登陆信息 var data = { // body: that.data.inputValue, "Name" : that.data.wo, "content" : "login" , "type" : 4 } that.sendSocketMessage(data); //循环发送心跳 setInterval( function () { var ping = { "type" : "ping" }; that.sendSocketMessage(ping); }, 20000 ); }) SocketTask.onClose(onClose => { console.log( '监听 WebSocket 连接关闭事件。' , onClose) socketOpen = false ; this .webSocket() }) SocketTask.onError(onError => { console.log( '监听 WebSocket 错误。错误信息' , onError) socketOpen = false }) SocketTask.onMessage(onMessage => { console.log( "onMessage:::::" + onMessage.data); if (onMessage.data.indexOf( "上线" ) != -1 || onMessage.data.indexOf( "下线" ) != -1) { return ; } console.log( '监听WebSocket接受到服务器的消息事件。服务器返回的消息' , JSON.parse(onMessage.data)) var onMessage_data = JSON.parse(onMessage.data) if (onMessage_data.toName == that.data.wo && onMessage_data.name == that.data.ta) { // addmsglist1(msg1.name, msg1.content) that.data.allContentList.push({ "id" : "" , "hx_id" : "" , "wo" : that.data.ta, "ta" : that.data.wo, "content" : onMessage_data.content, "voice_url" : "" , "fileurl" : null , "create_date" : "2019-12-03" }); that.setData({ allContentList: that.data.allContentList }) } }) }, onShow: function () { if (!socketOpen) { this .webSocket() } }, webSocket: function () { const that = this ; // 创建Socket SocketTask = wx.connectSocket({ url: url, data: 'data' , header: { 'content-type' : 'application/json' }, method: 'post' , success: function (res) { console.log( 'WebSocket连接创建' , res) }, fail: function (err) { wx.showToast({ title: '网络异常!' , }) console.log(err) }, }) }, onHide: function () { SocketTask.close( function (res) { console.log(res); }) }, onUnload: function () { SocketTask.close( function (res) { console.log(res); }) } }) |
能够建立起连接,但是后续方法都没用,监听SocketTask.onOpen方法,监听不到,SocketTask.onMessage方法也监听不到
我是偶尔能触发SocketTask.onOpen()
请问这个问题解决了吗
麻烦提供出现问题的具体机型、微信版本号、系统版本号,以及能复现问题的代码片段(https://developers.weixin.qq.com/miniprogram/dev/devtools/minicode.html)