• js封装一个websocket


    原文:https://www.jianshu.com/p/938004c22ed9

    创建websocket.js

    let Socket = ''
    let setIntervalWesocketPush = null
    

    /**

    • 建立websocket连接
    • @param {string} url ws地址
      */
      export const createSocket = url => {
      Socket && Socket.close()
      if (!Socket) {
      console.log('建立websocket连接')
      Socket = new WebSocket(url)
      Socket.onopen = onopenWS
      Socket.onmessage = onmessageWS
      Socket.onerror = onerrorWS
      Socket.onclose = oncloseWS
      } else {
      console.log('websocket已连接')
      }
      }

    /**打开WS之后发送心跳 */
    const onopenWS = () => {
    sendPing()
    }

    /**连接失败重连 */
    const onerrorWS = () => {
    Socket.close()
    clearInterval(setIntervalWesocketPush)
    console.log('连接失败重连中')
    if (Socket.readyState !== 3) {
    Socket = null
    createSocket()
    }
    }

    /**WS数据接收统一处理 */
    const onmessageWS = e => {
    window.dispatchEvent(new CustomEvent('onmessageWS', {
    detail: {
    data: e.data
    }
    }))
    }

    /**

    • 发送数据但连接未建立时进行处理等待重发
    • @param {any} message 需要发送的数据
      */
      const connecting = message => {
      setTimeout(() => {
      if (Socket.readyState === 0) {
      connecting(message)
      } else {
      Socket.send(JSON.stringify(message))
      }
      }, 1000)
      }

    /**

    • 发送数据
    • @param {any} message 需要发送的数据
      */
      export const sendWSPush = message => {
      if (Socket ! null && Socket.readyState = 3) {
      Socket.close()
      createSocket()
      } else if (Socket.readyState = 1) {
      Socket.send(JSON.stringify(message))
      } else if (Socket.readyState = 0) {
      connecting(message)
      }
      }

    /断开重连 */
    const oncloseWS = () => {
    clearInterval(setIntervalWesocketPush)
    console.log('websocket已断开....正在尝试重连')
    if (Socket.readyState !== 2) {
    Socket = null
    createSocket()
    }
    }
    /
    发送心跳

    • @param {number} time 心跳间隔毫秒 默认5000
    • @param {string} ping 心跳名称 默认字符串ping
      */
      export const sendPing = (time = 5000, ping = 'ping') => {
      clearInterval(setIntervalWesocketPush)
      Socket.send(ping)
      setIntervalWesocketPush = setInterval(() => {
      Socket.send(ping)
      }, time)
      }

    下载 (也可复制源码,放在本地,使用方式相同)

    npm install @sven0706/websocket -S
    

    使用

    
    // 在main.js或需要使用的地方引入并建立连接
    import { createSocket } from '@sven0706/websocket'
    createSocket('wss://api.baidu.com')
    

    // 发送消息
    import { sendWSPush } from '@sven0706/websocket'
    sendWSPush(data)

    // 接收消息
    const getsocketData = e => { // 创建接收消息函数
    const data = e && e.detail.data
    console.log(data)
    }
    // 注册监听事件
    window.addEventListener('onmessageWS', getsocketData)

    // 在需要的时候卸载监听事件,比如离开页面
    window.removeEventListener('onmessageWS', getsocketData)

    API

    仅三个api, 且一般只需要用到`createSocket`, `sendWSPush`
    

    /**

    • 建立websocket连接
    • @param {string} url ws地址
      */
      createSocket(url)

    /**

    • 发送数据
    • @param {any} message 需要发送的数据
      */
      sendWSPush(message)

    /**发送心跳

    • @param {number} time 心跳间隔毫秒 默认5000
    • @param {string} ping 心跳名称 默认字符串ping
      */
      sendPing()
  • 相关阅读:
    实体类中的date类型问题
    java.sql.SQLException: validateConnection false
    本地计算机的mysql服务启动后停止
    VUE遇到Windows 64-bit with Unsupported runtime (64) For more information on which environments are supported please see
    有关详细信息, 请使用 -Xlint:unchecked 重新编译。
    mysql出错ERROR 2003 (HY000): Can't connect to MySQL server on 'localhost' (10061)
    WIN7系统如何在文件列表中显示文件夹后缀
    shell 两类执行方法
    Git 报错 error setting certificate verify locations
    maven打包不同jdk版本的包
  • 原文地址:https://www.cnblogs.com/showcase/p/14000101.html
Copyright © 2020-2023  润新知