websocket 前端+后端

95 阅读1分钟

Websocket 基础配置笔记🧐

  • 全双工通信技术

😆前端配置

/**
* describe 发送 websocket.send() 需要使用JSON.stringify(params)
* readyState 0:未连接 1:连接 2:断开连接中 3:断开连接
*/
const websocket = new WebSocket('ws://localhost:5000')

websocket.onopen = () => {
    //设置心跳机制
}

//接听来自服务的的message
websocket.onmessage = (msg) => {
   //数据来源需解析
   const data = JSON.parse(msg.data)
} 

websocket.onclose = () => {
    //设置重连
} 

websocket.onerror = () => {
    //设置重连
}

//发送数据 
websocket.send(JSON.stringify(data))

😈后端配置

/**
* params
* describe 发送 ws.send() 需要使用JSON.stringify(params)
*/
const express = require('express')

const websocket = require('ws').server

const port = '5000'

const wss = websoket({port},(ws)=>{
      console.log('开启websocket服务:http://localhost:' + port)
})

//连接成功 内部设置监听
wss.on('connect',(ws)=>{
    
    ws.on('message', onMessage)
    
    ws.on('close', onClose)
    
    ws.on('error', onError)
    
})

const onMessage = (msg) => {
    console.log('相应数据')
}

const onClose = () => {
    console.log('关闭连接')
}

const onError = () => {
    console.log('报错')
}

// 广播
const boradcast = (msg) => {
    wss.clients.forEach(v => {
        v.send(JSON.stringify(msg))
    })
}

💓心跳包配置

const heartWrap = {
    time: 3000,
    timer: null
    state: 'ping'
}

const heartWrapStart = () => {
    heartWrap.timer = setInterval(() => {
        // 重启 websocket
    }, heartWrap.time)
}

const heartWrapStop = () => {
    clearInterval(hearWrap.timer)
    hearWrap.timer = null
}

逻辑梳理

前端 👉 后端

防断连:心跳机制

重连:1、判断是否连接 2、是否断开

心跳机制:(空包传递)

1、客户端连接websocket后开启定时心跳包发送 服务端接收到心跳包返回对应值

2、客户端发送后未收到服务端返回,开启重连

重连机制:

1、客户端连接完成给予一个标识isReconnect:false,当服务的断开 标识isReconnect:ture事件close处理重连

2、客户端开启重连,如未连接则继续定时重连,直到连接完成标识isReconnect:false