当前位置:网站首页>uniapp---初步使用websocket(长链接实现)
uniapp---初步使用websocket(长链接实现)
2022-07-04 09:38:00 【企鹅要去银河思考人生!!!】
onLoad() {
this.connectSocketInit()
},
// // 进入这个页面的时候创建websocket连接【整个页面随时使用】
connectSocketInit() {
//判断当前是否有websocket连接,如果有的话不在走创建sock方法
let socketTaskIsOpen = uni.getStorageSync("socketTaskIsOpen")
if (socketTaskIsOpen != "") return
// // 创建一个this.socketTask对象【发送、接收、关闭socket都由这个对象操作】
this.socketTask = uni.connectSocket({
// 【非常重要】必须确保你的服务器是成功的,如果是手机测试千万别使用ws://127.0.0.1:9099【特别容易犯的错误】
url: config.monitorSocketBaseUrl,
success(data) {
console.log("是否在线websocket连接成功");
uni.setStorageSync('socketTaskIsOpen', true)
},
})
//这里对这个方法赋值是为了将这些方法进行拆分,防止一个初始化方法中拥有太多的代码。
this.socketTaskIsOpen = true;
this.socketTask.onOpen = this.connectSocketOnOpen();
this.socketTask.onClose = this.connectSocketonClose()
this.socketTask.onMessage = this.connectSocketonMessage();
this.socketTask.onError = this.connectSocketonError()
},
// 打开时发送消息
connectSocketOnOpen(e) {
// 消息的发送和接收必须在正常连接打开中,才能发送或接收【否则会失败】
// 注:只有连接正常打开中 ,才能正常成功发送消息
var jsonObject = uni.getStorageSync("MonitorInfo")
// 如果要将json的格式通过websocket发送过去需要通过
// json。stringfy() 来进行转化
var jsonString = JSON.stringify(jsonObject)
// 这里的timer 组件实现的是一个长链接,通过每间隔一段时间来进行发送数据包。
this.timer = setInterval(() => {
try {
this.getMonitorInfo()
jsonObject = uni.getStorageSync("MonitorInfo")
jsonString = JSON.stringify(jsonObject)
this.socketTask.send({
data: jsonString,
async success() {
console.log("是否在线消息发送成功");
},
});
} catch (err) {
console.log('是否在线websocket断开了:' + err);
}
}, 15000)
},
connectSocketonClose(e) {
// 这里仅是事件监听【如果socket关闭了会执行】
this.socketTask.onClose(() => {
uni.setStorageSync('socketTaskIsOpen', false)
console.log("是否在线websocket已经被关闭了")
})
},
//监听服务器事件
connectSocketonMessage(e) {},
//连接建立失败重连
connectSocketonError(e) {
// this.connectSocketInit();
}注意事项:
1.如果要将json的格式通过websocket发送过去需要通过 json。stringfy() 来进行转化才可进行发送
2.长链接的实现是通过在websocketOnOpen方法中增加一个计时器来通过间隔时间来进行发送。
3.connectSocketInit()方法中进行判断是否有sock链接,如果有的话不在进行创建socket
4.connectSocketInit()方法中对onOpen,onClose,onMessage进行了查分,防止各个方法进行耦合。
边栏推荐
- Svg image quoted from CodeChina
- On Multus CNI
- libmysqlclient.so.20: cannot open shared object file: No such file or directory
- How do microservices aggregate API documents? This wave of show~
- JDBC and MySQL database
- 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
- el-table单选并隐藏全选框
- Qtreeview+ custom model implementation example
- Hands on deep learning (42) -- bi-directional recurrent neural network (BI RNN)
- Laravel文档阅读笔记-How to use @auth and @guest directives in Laravel
猜你喜欢

Histogram equalization

Hands on deep learning (40) -- short and long term memory network (LSTM)

Kubernetes CNI 插件之Fabric

MATLAB小技巧(25)竞争神经网络与SOM神经网络

用数据告诉你高考最难的省份是哪里!

Hands on deep learning (45) -- bundle search

C language pointer classic interview question - the first bullet

华为联机对战如何提升玩家匹配成功几率

Dynamic address book

C # use gdi+ to add text to the picture and make the text adaptive to the rectangular area
随机推荐
Exercise 7-8 converting strings to decimal integers (15 points)
Golang defer
【leetcode】540. A single element in an ordered array
Ruby时间格式转换strftime毫秒匹配格式
MySQL transaction mvcc principle
Exercise 7-2 finding the maximum value and its subscript (20 points)
对于程序员来说,伤害力度最大的话。。。
Hands on deep learning (46) -- attention mechanism
Exercise 9-1 time conversion (15 points)
智慧路灯杆水库区安全监测应用
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
PHP student achievement management system, the database uses mysql, including source code and database SQL files, with the login management function of students and teachers
el-table单选并隐藏全选框
Regular expression (I)
Dynamic address book
How to teach yourself to learn programming
Log cannot be recorded after log4net is deployed to the server
Pcl:: fromrosmsg alarm failed to find match for field 'intensity'
2. Data type
Four common methods of copying object attributes (summarize the highest efficiency)