vue3+ts 使用WebSocket

 封装WebSocket.ts

// '@/utils/WebSocketService';

export class WebSocketService {
  private socket: WebSocket | null = null;
  private url: string;

  constructor(url: string) {
    this.url = url;
  }

  public connect(): void {
    if (this.socket) {
      console.log('WebSocket已经连接上了');
      return;
    }

    this.socket = new WebSocket(this.url);

    this.socket.onopen = () => {
      console.log('已连接WebSocket');
      // 可以在这里发送一些初始化消息
    };

    this.socket.onmessage = (event) => {
      console.log('接收到的消息:', event.data);

      // 通过事件派发等方式通知 Vue 组件
      window.dispatchEvent(
        new CustomEvent('onmessageWS', {
          detail: {
            data: event.data
          }
        })
      );

    };

    this.socket.onerror = (error) => {
      console.error('WebSocket中的错误:', error);
    };

    this.socket.onclose = () => {
      console.log('已断开WebSocket连接');
      // 可以尝试重新连接
    };
  }

  public disconnect(): void {
    if (this.socket) {
      this.socket.close();
      this.socket = null;
    }
  }

  // 可以添加其他方法,如发送消息
  public sendMessage(message: string): void {
    if (this.socket && this.socket.readyState === WebSocket.OPEN) {
      this.socket.send(message);
    } else {
      console.error('WebSocket未连接');
    }
  }
}

使用WebSocket

<template>
  <div>
    <h1>WebSocket Demo</h1>
    <el-input v-model="messageToSend" />
    <button @click="sendMessageToServer">Send Message to Server</button>
  </div>
</template>

<script lang="ts" setup>
import { defineComponent, onMounted, onUnmounted, ref } from 'vue';
import { WebSocketService } from '@/utils/WebSocketService';

const wsService = new WebSocketService('ws://x-tool.online:8082/ws');
const messageToSend = ref(''); // 假设你有一个输入框来输入消息,这里用 ref 代替

// 监听事件
window.addEventListener('onmessageWS', (event: any) => {
  console.log('vue组件接受到的数据', event.detail.data);
});

// 组件挂载时连接 WebSocket
onMounted(() => {
  wsService.connect();
});

// 组件卸载时断开 WebSocket
onUnmounted(() => {
  wsService.disconnect();
});

// 发送消息到服务器的方法
const sendMessageToServer = () => {
  wsService.sendMessage(messageToSend.value);
};
</script>

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,针对你的问题,我可以给你一些思路和建议: 1. 首先,你需要了解 WebSocket 协议的基本原理和使用方法。WebSocket 是一种基于 TCP 协议的双向通信协议,它可以在客户端和服务器之间建立长连接,实现实时通信。 2. 接下来,你需要在 Vue3 项目中安装 WebSocket 相关的库。常用的 WebSocket 库有 `socket.io-client`、`ws` 等,你可以根据自己的需求选择合适的库进行安装和使用。 3. 在 Vite 中使用 TypeScript 也是很简单的。你只需要在项目中安装 `typescript` 和 `@vitejs/plugin-vue`,然后配置 `tsconfig.json` 文件和 `vite.config.ts` 文件即可。 4. 在 Vue3 中使用 WebSocket 也很方便。你可以在组件中使用 `created()` 或 `mounted()` 钩子函数来创建 WebSocket 连接,并在 `beforeUnmount()` 钩子函数中关闭 WebSocket 连接。 下面是一个简单的示例代码,供你参考: ```typescript <template> <div> <p>{{ message }}</p> </div> </template> <script lang="ts"> import { defineComponent } from 'vue'; import io from 'socket.io-client'; export default defineComponent({ data() { return { message: '', }; }, mounted() { const socket = io('ws://localhost:3000'); socket.on('connect', () => { console.log('WebSocket Connected!'); }); socket.on('message', (data: string) => { this.message = data; }); }, beforeUnmount() { // 关闭 WebSocket 连接 socket.close(); }, }); </script> ``` 以上就是使用 Vue3 + Vite + TypeScript 实现 WebSocket 的基本思路和方法。希望对你有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一路向北. 

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值