前端websocket使用

本文介绍了如何在前端JavaScript中使用WebSocket进行实时通信,包括初始化连接、数据发送、错误处理和断开连接的处理逻辑。重点在于`fun_websocket`函数和相关事件处理方法的实现。
摘要由CSDN通过智能技术生成
fun_websocket() {
  this.loadingImg = true
  // 初始化weosocket
  const wsuriImg = 'ws://' + window.ipConfig.IMG_RECOGNITION_URL
  this.websockImg = new WebSocket(wsuriImg)
  this.websockImg.onopen = this.websocketonopenImg
  this.websockImg.onerror = this.websocketonerrorImg
  this.websockImg.onmessage = this.websocketonmessageImg
  this.websockImg.onclose = this.websocketcloseImg
},
// 连接建立之后执行send方法发送数据
websocketonopenImg() {
  const obj = {}
  // 数据发送
  this.websockImg.send(JSON.stringify(obj))
},
// 连接建立失败重连
websocketonerrorImg() {
  this.loading = false
  console.log('连接建立失败重连')
  // this.fun_websocket()
},
// 数据接收
websocketonmessageImg(e) {
  this.loading = false
  console.log(e.data)
},
// 关闭
websocketcloseImg() {
  this.websockImg.close()
  console.log('关闭---')
},

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值