<template>
<view class="websockets">
<button type="primary" @tap="clickRequest">點擊發(fā)送請求</button>
<button type="primary" @tap="leave">離開頁面</button>
</view>
</template>
<script>
export default {
onLoad() {
// 進入這個頁面的時候創(chuàng)建websocket連接【整個頁面隨時使用】
this.connectSocketInit();
},
data() {
return {
socketTask: null,
// 確保websocket是打開狀態(tài)
is_open_socket: false
}
},
// 關閉websocket【必須在實例銷毀之前關閉,否則會是underfined錯誤】
beforeDestroy() {
this.closeSocket();
},
methods: {
// 進入這個頁面的時候創(chuàng)建websocket連接【整個頁面隨時使用】
connectSocketInit() {
// 創(chuàng)建一個this.socketTask對象【發(fā)送、接收、關閉socket都由這個對象操作】
this.socketTask = uni.connectSocket({
// 【非常重要】必須確保你的服務器是成功的,如果是手機測試千萬別使用ws://127.0.0.1:9099【特別容易犯的錯誤】
url: "ws://119.28.180.110:9099/echo",
success(data) {
console.log("websocket連接成功");
},
});
// 消息的發(fā)送和接收必須在正常連接打開中,才能發(fā)送或接收【否則會失敗】
this.socketTask.onOpen((res) => {
console.log("WebSocket連接正常打開中...!");
this.is_open_socket = true;
// 注:只有連接正常打開中 ,才能正常成功發(fā)送消息
this.socketTask.send({
data: "uni-app發(fā)送一條消息",
async success() {
console.log("消息發(fā)送成功");
},
});
// 注:只有連接正常打開中 ,才能正常收到消息
this.socketTask.onMessage((res) => {
console.log("收到服務器內(nèi)容:" + res.data);
});
})
// 這里僅是事件監(jiān)聽【如果socket關閉了會執(zhí)行】
this.socketTask.onClose(() => {
console.log("已經(jīng)被關閉了")
})
},
// 關閉websocket【離開這個頁面的時候執(zhí)行關閉】
closeSocket() {
this.socketTask.close({
success(res) {
this.is_open_socket = false;
console.log("關閉成功", res)
},
fail(err) {
console.log("關閉失敗", err)
}
})
},
clickRequest() {
if (this.is_open_socket) {
// websocket的服務器的原理是:發(fā)送一次消息,同時返回一組數(shù)據(jù)【否則服務器會進去死循環(huán)崩潰】
this.socketTask.send({
data: "請求一次發(fā)送一次message",
async success() {
console.log("消息發(fā)送成功");
},
});
}
},
leave() {
this.$uniReLaunch("/pages/tabbar/wallet/wallet")
}
}
}
</script>
原文鏈接:https://blog.csdn.net/weixin_43343144/article/details/92998467文章來源地址http://www.zghlxwxcb.cn/news/detail-723926.html
文章來源:http://www.zghlxwxcb.cn/news/detail-723926.html
到了這里,關于uni-app使用websocket的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!