uniApp使用websocket


 

 

/*可以选择点击也可以选择页面加载调用*/

onLoad() {
this.connect();
},

/*页面卸载关闭websocket*/
onUnload() {
uni.closeSocket()
uni.hideLoading()
},

/*调用方法 连接  注意 是使用ws或者wss

  wss不能用ip地址

*/

connect() {
if (this.connected || this.connecting) {
uni.showModal({
content: '正在连接或者已经连接,请勿重复连接',
showCancel: false
})
return false
}
this.connecting = true
uni.showLoading({
title: '连接中...'
})
uni.connectSocket({
url: 'wss://echo.websocket.org',
data() {
return {
msg: 'Hello'
}
},
// header: {
// 'content-type': 'application/json',
// "X-Access-Token":'000000000000000000000'
// },
// #ifdef MP
header: {
'content-type': 'application/json'
},
// #endif
// #ifdef MP-WEIXIN
method: 'GET',
// #endif
success(res) {
// 这里是接口调用成功的回调,不是连接成功的回调,请注意
},
fail(err) {
// 这里是接口调用失败的回调,不是连接失败的回调,请注意
}
})
uni.onSocketOpen((res) => {
this.connecting = false
this.connected = true
uni.hideLoading()
uni.showToast({
icon: 'none',
title: '连接成功'
})
console.log('onOpen', res);
})
uni.onSocketError((err) => {
this.connecting = false
this.connected = false
uni.hideLoading()
uni.showModal({
content: '连接失败,可能是websocket服务不可用,请稍后再试',
showCancel: false
})
console.log('onError', err);
})
uni.onSocketMessage((res) => {
this.msg = res.data
console.log('onMessage', res)
})
uni.onSocketClose((res) => {
this.connected = false
this.startRecive = false
this.msg = false
console.log('onClose', res)
})
},

/*调用发送数据方法  这里是模拟的值*/

send() {
uni.sendSocketMessage({
data: 'from ' + platform + ' : ' + parseInt(Math.random() * 10000).toString(), 
success(res) {
console.log(res);
},
fail(err) {
console.log(err);
}
})
},

/*调用关闭方法*/
close() {
uni.closeSocket()
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM