当前位置:网站首页>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进行了查分,防止各个方法进行耦合。
边栏推荐
- Leetcode (Sword finger offer) - 35 Replication of complex linked list
- mmclassification 标注文件生成
- Exercise 9-3 plane vector addition (15 points)
- libmysqlclient.so.20: cannot open shared object file: No such file or directory
- Servlet基本原理与常见API方法的应用
- A little feeling
- Baidu R & D suffered Waterloo on three sides: I was stunned by the interviewer's set of combination punches on the spot
- What are the advantages of automation?
- Write a mobile date selector component by yourself
- Hands on deep learning (46) -- attention mechanism
猜你喜欢

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

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

Write a mobile date selector component by yourself

Hands on deep learning (39) -- gating cycle unit Gru

Daughter love: frequency spectrum analysis of a piece of music

C # use gdi+ to add text to the picture and make the text adaptive to the rectangular area

Nuxt reports an error: render function or template not defined in component: anonymous

pcl::fromROSMsg报警告Failed to find match for field ‘intensity‘.

H5 audio tag custom style modification and adding playback control events

2. Data type
随机推荐
百度研发三面惨遭滑铁卢:面试官一套组合拳让我当场懵逼
How can people not love the amazing design of XXL job
Log cannot be recorded after log4net is deployed to the server
Hands on deep learning (42) -- bi-directional recurrent neural network (BI RNN)
Lauchpad x | MODE
Golang type comparison
技术管理进阶——如何设计并跟进不同层级同学的绩效
Web端自动化测试失败原因汇总
Hands on deep learning (34) -- sequence model
ASP. Net to access directory files outside the project website
Exercise 9-5 address book sorting (20 points)
C # use gdi+ to add text to the picture and make the text adaptive to the rectangular area
六月份阶段性大总结之Doris/Clickhouse/Hudi一网打尽
Hands on deep learning (36) -- language model and data set
2. Data type
Kotlin set operation summary
Kotlin 集合操作汇总
libmysqlclient.so.20: cannot open shared object file: No such file or directory
AUTOSAR from getting started to mastering 100 lectures (106) - SOA in domain controllers
Hands on deep learning (35) -- text preprocessing (NLP)