当前位置:网站首页>Uniapp--- initial use of websocket (long link implementation)
Uniapp--- initial use of websocket (long link implementation)
2022-07-04 10:03:00 【Penguin wants to go to galaxy to think about life!!!】
onLoad() {
this.connectSocketInit()
},
// // When you enter this page, create websocket Connect 【 The whole page is ready to use 】
connectSocketInit() {
// Judge whether there is websocket Connect , If any, don't go create sock Method
let socketTaskIsOpen = uni.getStorageSync("socketTaskIsOpen")
if (socketTaskIsOpen != "") return
// // Create a this.socketTask object 【 send out 、 receive 、 close socket Are manipulated by this object 】
this.socketTask = uni.connectSocket({
// 【 It's very important 】 Make sure your server is successful , If it's a mobile phone test, don't use it ws://127.0.0.1:9099【 A particularly easy mistake to make 】
url: config.monitorSocketBaseUrl,
success(data) {
console.log(" Whether online websocket Successful connection ");
uni.setStorageSync('socketTaskIsOpen', true)
},
})
// This method is assigned a value here to split these methods , Prevent too much code in an initialization method .
this.socketTaskIsOpen = true;
this.socketTask.onOpen = this.connectSocketOnOpen();
this.socketTask.onClose = this.connectSocketonClose()
this.socketTask.onMessage = this.connectSocketonMessage();
this.socketTask.onError = this.connectSocketonError()
},
// Send message when opening
connectSocketOnOpen(e) {
// The sending and receiving of messages must be in normal connection , To send or receive 【 Otherwise it will fail 】
// notes : Only the connection is normally open , To send messages normally and successfully
var jsonObject = uni.getStorageSync("MonitorInfo")
// If you want to json Format through websocket Send the past through
// json.stringfy() To transform
var jsonString = JSON.stringify(jsonObject)
// there timer The component implements a long link , Send packets at intervals .
this.timer = setInterval(() => {
try {
this.getMonitorInfo()
jsonObject = uni.getStorageSync("MonitorInfo")
jsonString = JSON.stringify(jsonObject)
this.socketTask.send({
data: jsonString,
async success() {
console.log(" Whether the online message was sent successfully ");
},
});
} catch (err) {
console.log(' Whether online websocket Disconnect the :' + err);
}
}, 15000)
},
connectSocketonClose(e) {
// This is just event monitoring 【 If socket If it is closed, it will execute 】
this.socketTask.onClose(() => {
uni.setStorageSync('socketTaskIsOpen', false)
console.log(" Whether online websocket It's closed ")
})
},
// Listen for server events
connectSocketonMessage(e) {},
// Connection establishment failed to reconnect
connectSocketonError(e) {
// this.connectSocketInit();
}matters needing attention :
1. If you want to json Format through websocket Send the past through json.stringfy() To convert before sending
2. Long links are achieved by websocketOnOpen Method to send by interval time .
3.connectSocketInit() Method to determine whether there is sock link , If any, it is not being created socket
4.connectSocketInit() Method for onOpen,onClose,onMessage Checked and scored , Prevent various methods from coupling .
边栏推荐
- Vanishing numbers
- MongoDB数据日期显示相差8小时 原因和解决方案
- Write a mobile date selector component by yourself
- 2021-08-10 character pointer
- Get the source code in the mask with the help of shims
- leetcode1-3
- Intelligent gateway helps improve industrial data acquisition and utilization
- mmclassification 标注文件生成
- Advanced technology management - how to design and follow up the performance of students at different levels
- Hands on deep learning (44) -- seq2seq principle and Implementation
猜你喜欢

Summary of small program performance optimization practice

【Day2】 convolutional-neural-networks

5g/4g wireless networking scheme for brand chain stores

基于线性函数近似的安全强化学习 Safe RL with Linear Function Approximation 翻译 1

【OpenCV 例程200篇】218. 多行倾斜文字水印

Daughter love in lunch box

SQL replying to comments

C语言指针面试题——第二弹

Pcl:: fromrosmsg alarm failed to find match for field 'intensity'

入职中国平安三周年的一些总结
随机推荐
xxl-job惊艳的设计,怎能叫人不爱
How can people not love the amazing design of XXL job
智慧路灯杆水库区安全监测应用
用数据告诉你高考最难的省份是哪里!
Exercise 9-3 plane vector addition (15 points)
Vanishing numbers
Hands on deep learning (36) -- language model and data set
Log cannot be recorded after log4net is deployed to the server
PHP book borrowing management system, with complete functions, supports user foreground management and background management, and supports the latest version of PHP 7 x. Database mysql
Nuxt reports an error: render function or template not defined in component: anonymous
Sort out the power node, Mr. Wang he's SSM integration steps
Kubernetes CNI 插件之Fabric
What are the advantages of automation?
PHP代码审计3—系统重装漏洞
MySQL transaction mvcc principle
Hands on deep learning (42) -- bi-directional recurrent neural network (BI RNN)
直方图均衡化
C language pointer classic interview question - the first bullet
Pueue data migration from '0.4.0' to '0.5.0' versions
六月份阶段性大总结之Doris/Clickhouse/Hudi一网打尽