Vue3 は WebSocket を使用します (プロテスト ソリューション)

1. バックエンドは次のような ws インターフェイスを提供する必要があります。

ws://192.168.2.19:8080/chat/${name}

ここの私の名前はログイン成功後のバックエンドリクエストです

2. バックエンドはログイン インターフェイスを提供します。長いリンクを実現するにはログインする必要があります。

const login = (name) => {
  toLogin(data).then(res => {
    console.log(res);
    init(name)
  }).catch(err => {
    console.log(err);
  })
}

3. init メソッドをカプセル化する

const init = (name) => {
  if(typeof(WebSocket) === "undefined"){
      alert("您的浏览器不支持socket")
  }else{
     const ws = new WebSocket(`ws://192.168.2.19:8080/chat/${name}`)
    //  //连接发生错误的回调方法
    ws.onerror = function () {
      console.log("ws连接发生错误");
    };
    //连接成功建立的回调方法
    ws.onopen = function () {
      console.log("ws连接成功");
    }
    //接收到消息的回调方法
    ws.onmessage = function (event) {
      console.log(name + '的',event.data);
    }
    //连接关闭的回调方法
    ws.onclose = function () {
      console.log("ws连接关闭");
    }
  }
}

インターネット上で無駄な方法をたくさん見つけました。読むことはお勧めしません

全コード集

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import {toLogin} from '../http/index'

let word = ref('')
const data = {
  username:'zhangsan',
  password:'123'
}
const login = (name) => {
  toLogin(data).then(res => {
    console.log(res);
    init(name)
  }).catch(err => {
    console.log(err);
  })
}
const init = (name) => {
  if(typeof(WebSocket) === "undefined"){
      alert("您的浏览器不支持socket")
  }else{
     const ws = new WebSocket(`ws://192.168.2.19:8080/chat/${name}`)
    //  //连接发生错误的回调方法
    ws.onerror = function () {
      console.log("ws连接发生错误");
    };
    //连接成功建立的回调方法
    ws.onopen = function () {
      console.log("ws连接成功");
    }
    //接收到消息的回调方法
    ws.onmessage = function (event) {
      console.log(name + '的',event.data);
    }
    //连接关闭的回调方法
    ws.onclose = function () {
      console.log("ws连接关闭");
    }
  }
}
</script>

<template>
  <h1>Web Socket</h1>
  <div>聊天框 <textarea type="text" v-model="word" ></textarea></div>
  <button @click="login('zhangsan')">张三登录</button>
  <button @click="login('李四')">李四登录</button>
  <button @click="send">发送</button>
</template>

<style scoped>
</style>

おすすめ

転載: blog.csdn.net/ZHANG157111/article/details/130949644