vue2 使用 Socket.io 实现 WebSocket

使用 NPM:

官网:https://socket.io/zh-CN/docs/v4/
客户端API:https://socket.io/zh-CN/docs/v4/client-api/#socket

1、安装 Socket.io 客户端

首先,在你的 Vue 项目中安装 socket.io-client:

npm install socket.io-client
2、在 Vue 组件中使用 Socket.io

在你的 Vue 组件中,可以像这样使用 Socket.io:

import io from 'socket.io-client';
// import { io } from "socket.io-client";

export default {
  data() {
    return {
      socket: null
    };
  },
  created() {
    this.init()
  },
  methods: {
    init(){
        // 1. 连接到服务器
        // 来自不同域,请确保在服务器上启用 跨域资源共享 (CORS)。
        this.socket = io("https://server-domain.com");
        // 来自同域
        // this.socket = io();
        
        console.log(this.socket.id); // undefined
        
        // 连接服务器
        this.socket.on('connect', () => {
            console.log('已连接到服务器',this.socket.id);// "G5p5..."
        });
    
        // 2. 监听来自服务器的消息, 服务的的事件名 'news'
        this.socket.on('news', (data) => {
          console.log(data);
        });
        
        // 5. 断开连接时自动重连
        // this.socket.on("disconnect", () => {
        //   this.socket.connect();
        // });
    },
    // 发送消息按钮
    sendMessage(message) {
        // 检查连接状态
        if (this.socket.connected) {
            // 如果已连接,则直接发送任务信号
            let post_data = {name: 'test'}
            
            // 3. 发送消息到服务器, 'message' 客户端事件名
            this.socket.emit('message', post_data, (response) => {
                console.log(response); // "got it"
            });
        } else {
            // 如果断开连接,则尝试重新连接
            this.socket.connect();
            
            // 监听连接成功事件
            this.socket.on('connect', function() {
                // 连接成功后发送任务信号
                let post_data = {name: 'test'}
                
                // 3. 发送消息到服务器, 'message' 客户端事件名
                this.socket.emit('message', post_data, (response) => {
                    console.log(response); // "got it"
                });
            });
        }
    }
  },
  beforeDestroy() {
    // 4. 断开连接
    if (this.socket) {
        this.socket.disconnect();
    }
  }
};

  • created() 钩子用来连接到服务器并设置消息监听器。
  • sendMessage() 方法用来发送消息到服务器。
  • beforeDestroy() 钩子在组件销毁前断开连接。

相关推荐

  1. vue2 使用 Socket.io 实现 WebSocket

    2024-07-11 20:36:06       24 阅读
  2. vue2 实现原生 WebSocket

    2024-07-11 20:36:06       20 阅读
  3. 前端实现websocket通信讲解(vue2框架)

    2024-07-11 20:36:06       47 阅读
  4. vue项目中封装并使用WebSocket(2)

    2024-07-11 20:36:06       40 阅读

最近更新

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

    2024-07-11 20:36:06       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-11 20:36:06       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-11 20:36:06       58 阅读
  4. Python语言-面向对象

    2024-07-11 20:36:06       69 阅读

热门阅读

  1. flink 大数据处理资源分配

    2024-07-11 20:36:06       19 阅读
  2. LiteOS GPIO中断处理

    2024-07-11 20:36:06       20 阅读
  3. python如何与前端交互

    2024-07-11 20:36:06       16 阅读
  4. 模型需要从txt中长文本中精准提炼出来文字

    2024-07-11 20:36:06       22 阅读
  5. vue3 学习笔记04 -- axios的使用及封装

    2024-07-11 20:36:06       24 阅读
  6. 大模型融入云平台,信息化走向数智化

    2024-07-11 20:36:06       20 阅读
  7. 开源项目有哪些机遇与挑战?

    2024-07-11 20:36:06       22 阅读
  8. 精通 mysqldumpslow:深度分析 MySQL 慢查询日志

    2024-07-11 20:36:06       22 阅读
  9. 定个小目标之刷LeetCode热题(41)

    2024-07-11 20:36:06       19 阅读
  10. 详细介绍一下TypeScript

    2024-07-11 20:36:06       23 阅读
  11. Ant-Vue——modal对话框

    2024-07-11 20:36:06       23 阅读
  12. windows 修改 npmrc

    2024-07-11 20:36:06       22 阅读