当前位置:网站首页>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进行了查分,防止各个方法进行耦合。
边栏推荐
- 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
- MySQL develops small mall management system
- AUTOSAR从入门到精通100讲(106)-域控制器中的SOA
- Hands on deep learning (34) -- sequence model
- H5 audio tag custom style modification and adding playback control events
- Regular expression (I)
- How do microservices aggregate API documents? This wave of show~
- libmysqlclient.so.20: cannot open shared object file: No such file or directory
- How web pages interact with applets
- Matlab tips (25) competitive neural network and SOM neural network
猜你喜欢
Hands on deep learning (44) -- seq2seq principle and Implementation
Devop basic command
对于程序员来说,伤害力度最大的话。。。
The child container margin top acts on the parent container
Fabric of kubernetes CNI plug-in
Summary of small program performance optimization practice
Mmclassification annotation file generation
技术管理进阶——如何设计并跟进不同层级同学的绩效
C # use gdi+ to add text with center rotation (arbitrary angle)
xxl-job惊艳的设计,怎能叫人不爱
随机推荐
View CSDN personal resource download details
Write a jison parser (7/10) from scratch: the iterative development process of the parser generator 'parser generator'
Golang Modules
AUTOSAR from getting started to mastering 100 lectures (106) - SOA in domain controllers
Implementing expired localstorage cache with lazy deletion and scheduled deletion
Launpad | 基礎知識
Deadlock in channel
C语言指针面试题——第二弹
Fatal error in golang: concurrent map writes
System. Currenttimemillis() and system Nanotime (), which is faster? Don't use it wrong!
[200 opencv routines] 218 Multi line italic text watermark
How to teach yourself to learn programming
Upgrading Xcode 12 caused Carthage to build cartfile containing only rxswift to fail
In the case of easyUI DataGrid paging, click the small triangle icon in the header to reorder all the data in the database
Whether a person is reliable or not, closed loop is very important
华为联机对战如何提升玩家匹配成功几率
Exercise 9-3 plane vector addition (15 points)
Latex download installation record
Rules for using init in golang
el-table单选并隐藏全选框