vue3如何发送 websocket 请求

封装 WebSocket 方法,并调用
let ws = ref(null)
const startWs = (sendInfo) => {
  // let ws = null
  function onOpen() {
    console.log("连接成功")
    // ws.value.send(sendInfo ? JSON.stringify(sendInfo) : null)
  }
  function onMessage(event) {
    if (event.data) {
      let ret = JSON.parse(JSON.parse(event.data).data)
      ret.from = JSON.parse(event.data).from
      ret.isBreakpoint = JSON.parse(event.data).isBreakpoint

      if (ret.isBreakpoint) {
        // 如果有新断点,则将上一个断点信息的isBreakpoint置为false
        let index = tableData.value.findIndex((item) => item.isBreakpoint)
        if (index > -1) tableData.value[index].isBreakpoint = false
        pauseAllocatedPort.value = ret.allocatedPort
      }
      tableData.value.push(ret)
      if (ret.isBreakpoint) {
        isBreakpoint.value = true
        // 当前为断点信息,存储nextData,并回显报文
        nextData.value = ret
        dataForm.textareashow = JSON.stringify(
          JSON.parse(ret.messageData),
          null,
          2
        )
      } else {
        isBreakpoint.value = false
      }
    //设置table滚动条始终在最下方
      setTimeout(() => {
        tableRef.value.scrollBarRef.wrapRef.scrollTop =
          tableRef.value.scrollBarRef.wrapRef.scrollHeight
      }, 0)
      
    // allocatedPortArr去重
      allocatedPortArr.value.push(ret.allocatedPort)
      allocatedPortArr.value = [...new Set(allocatedPortArr.value)]
    }
  }
  function onClose(event) {
    console.log("连接关闭")
  }
  function onError(event) {
    ElMessage.error("任务连接发生异常,可刷新页面重试")
  }
  function connect() {
    ws.value = new WebSocket("ws://127.0.0.1:12132/api/v0/web/stream/fe")
    ws.value.onopen = onOpen
    ws.value.onclose = onClose
    ws.value.onmessage = onMessage
    ws.value.onerror = onError
  }
  connect()
}
startWs()
在合适的时候,发送请求
// 不同情况下发的ws请求
const onSubmit = (val, data) =>{
switch (val) {
    case "1": //筛选
      ws.value.send(
        JSON.stringify({
          type,
          cmd: "filter",
          from: "fe",
          to: form.allocatedPort ? `be_${form.allocatedPort}` : null,
          data,
          time: Date.now()
        })
      )
      break
   default:
      break
}

你可能感兴趣的:(websocket,网络协议,网络)