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>

相关推荐

  1. vue3+ts 使用WebSocket

    2024-07-12 16:54:05       24 阅读
  2. Vue3 ts使用echarts

    2024-07-12 16:54:05       33 阅读
  3. vue3websocket的封装与使用

    2024-07-12 16:54:05       48 阅读
  4. <span style='color:red;'>vue</span><span style='color:red;'>3</span>+<span style='color:red;'>Ts</span>

    vue3+Ts

    2024-07-12 16:54:05      63 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-12 16:54:05       66 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-12 16:54:05       70 阅读
  3. 在Django里面运行非项目文件

    2024-07-12 16:54:05       57 阅读
  4. Python语言-面向对象

    2024-07-12 16:54:05       68 阅读

热门阅读

  1. Chubby VS Zookeeper

    2024-07-12 16:54:05       22 阅读
  2. 需求实现:字数限制500字

    2024-07-12 16:54:05       19 阅读
  3. 安全开发基础篇-数据溢出

    2024-07-12 16:54:05       25 阅读
  4. MySQL 用like “%x“,索引就一定会失效吗?

    2024-07-12 16:54:05       22 阅读
  5. Windows CMD 命令汇总表

    2024-07-12 16:54:05       17 阅读
  6. Spring Boot应用启动慢的原因分析及优化方法

    2024-07-12 16:54:05       22 阅读
  7. python工作中遇到的坑

    2024-07-12 16:54:05       23 阅读
  8. 算法面试题_字节

    2024-07-12 16:54:05       26 阅读
  9. CHD安装

    2024-07-12 16:54:05       22 阅读
  10. 开源项目有哪些机遇和挑战?

    2024-07-12 16:54:05       21 阅读
  11. 敏捷项目管理与PMP有什么区别?彻底说明白!

    2024-07-12 16:54:05       26 阅读