WXS
所有监听事件先在onload监听。
// pages/index/to_news/to_news.js
var app = getApp();
var socketOpen = false;
var SocketTask = false;
var url = 'ws://192.168.0.120:7011';
Page({
data: {
inputValue: '',
returnValue: '',
},
onLoad: function (options) {
},
onReady: function () {
// 创建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)
},
})
if (SocketTask) {
SocketTask.onOpen(res => {
console.log('监听 WebSocket 连接打开事件。', res)
})
SocketTask.onClose(onClose => {
console.log('监听 WebSocket 连接关闭事件。', onClose)
})
SocketTask.onError(onError => {
console.log('监听 WebSocket 错误。错误信息', onError)
})
SocketTask.onMessage(onMessage => {
console.log('监听WebSocket接受到服务器的消息事件。服务器返回的消息', onMessage)
})
}
},
// 提交文字
submitTo: function (e) {
let that = this;
that.data.allContentList.push({that.data.inputValue });
that.setData({
allContentList: that.data.allContentList
})
var data = {
text: that.data.inputValue
}
if (socketOpen) {
// 如果打开了socket就发送数据给服务器
sendSocketMessage(data)
}
},
bindKeyInput: function (e) {
this.setData({
inputValue: e.detail.value
})
},
onHide: function () {
SocketTask.close(function (close) {
console.log('关闭 WebSocket 连接。', close)
})
},
})
//通过 WebSocket 连接发送数据,需要先 wx.connectSocket,并在 wx.onSocketOpen 回调之后才能发送。
function sendSocketMessage(data) {
console.log('通过 WebSocket 连接发送数据')
if (socketOpen) {
SocketTask.send({data: JSON.stringify(data)
}, function (res) {
console.log('已发送', res)
})
} else {
socketMsgQueue.push(msg)
}
}
WXML
<input type="text" bindinput="bindKeyInput" value='{
{inputValue}}' placeholder="" />
<button bindtap="submitTo" class='user_input_text'>发送</button>