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() 钩子在组件销毁前断开连接。
相关推荐
haoshenwan17 小时前
WebSocket简单介绍 并接入deepseek
网络·websocket·网络协议
JIU_WW20 小时前
Netty内置的空闲检测机制
java·服务器·前端·websocket·netty
瓜皮弟子头很铁20 小时前
.net websocket 使用
网络·websocket·网络协议·.net
x-cmd1 天前
[250224] Yaak 2.0:Git集成、WebSocket支持、OAuth认证等 | Zstandard v1.5.7 发布
运维·git·websocket·网络协议·安全·oauth·压缩
Cleo_Gao2 天前
从零开始的网站搭建(以照片/文本/视频信息通信网站为例)
python·websocket·flask
仙八哥2 天前
Ubuntu搭建esp32环境 配置打开AT指令集 websocket功能
linux·websocket·ubuntu
27669582923 天前
快手弹幕 websocket 分析
java·python·websocket·go·快手·快手弹幕·ks
m0_748229993 天前
4.WebSocket 配置与Nginx 的完美结合
websocket·网络协议·nginx
看,未来5 天前
Apipost 与 Postman 工具实践指南:WebSocket调试与动态参数测试
websocket·测试工具·postman
哑巴语天雨5 天前
前端面试-网络协议篇
websocket·网络协议·http·面试·https