vue3使用websocket(亲测解决)

1.需要后端给你一个ws的接口比如:

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

我这里的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>

  • 6
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值