vue2 实现原生 WebSocket

原生WebSocket: new WebSocket

WebSocket | ThinkTS官网

export default {
  data() {
    return {
      socket: null
    };
  },
  created() {
    // 1. 创建 WebSocket 实例
    this.socket = new WebSocket('ws://localhost:3000');

    // 2. 监听 WebSocket 连接打开事件
    this.socket.onopen = () => {
        console.log('当前客户端已连接');
    };

    // 3. 监听 WebSocket 消息事件
    this.socket.onmessage = (event) => {
        console.log('客户端接收的数据:', JSON.parse(event.data));
        
        // 4. 发送消息给服务端
        let post_data = {name: 'test'}
        this.socket.send(JSON.stringify(post_data))
    };

    // 5. 监听 WebSocket 关闭事件
    this.socket.onclose = () => {
        console.log('WebSocket closed');
    };

    // 6. 监听 WebSocket 错误事件
    this.socket.onerror = (error) => {
        console.log('WebSocket error:', error);
    };
  },
  methods: {
    // 发送消息按钮
    sendMessage(message) {
        // 4. 发送消息到 WebSocket 服务器
        this.socket.send(JSON.stringify(message))
    }
  },
  beforeDestroy() {
    // 关闭 WebSocket 连接
    if (this.socket) {
        this.socket.close();
    }
  }
};

相关推荐

  1. vue2 实现原生 WebSocket

    2024-07-11 19:24:04       24 阅读
  2. vue2 使用 Socket.io 实现 WebSocket

    2024-07-11 19:24:04       24 阅读
  3. 前端实现websocket通信讲解(vue2框架)

    2024-07-11 19:24:04       47 阅读
  4. vue-socket.io以及原生websocket的使用

    2024-07-11 19:24:04       48 阅读
  5. websocket 实现原理和技术方案

    2024-07-11 19:24:04       48 阅读

最近更新

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

    2024-07-11 19:24:04       70 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-11 19:24:04       74 阅读
  3. 在Django里面运行非项目文件

    2024-07-11 19:24:04       62 阅读
  4. Python语言-面向对象

    2024-07-11 19:24:04       72 阅读

热门阅读

  1. 第五十章 Web Service URL 汇总

    2024-07-11 19:24:04       24 阅读
  2. MyEclipse不能自动编译解决方案

    2024-07-11 19:24:04       24 阅读
  3. Node.js path模块

    2024-07-11 19:24:04       20 阅读
  4. Node.js Stream

    2024-07-11 19:24:04       24 阅读
  5. 前端时间格式传入后端负载里面没有东西

    2024-07-11 19:24:04       24 阅读
  6. Spring如何控制Bean加载+执行顺序

    2024-07-11 19:24:04       22 阅读
  7. futures.toArray(new CompletableFuture[0])

    2024-07-11 19:24:04       23 阅读
  8. 远程Linux机器图形化界面使用及音频转发

    2024-07-11 19:24:04       26 阅读
  9. 【React Hooks原理 - useReducer】

    2024-07-11 19:24:04       20 阅读