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() 钩子在组件销毁前断开连接。
相关推荐
艾莉丝努力练剑2 天前
【AI大模型接入SDK】WebSocket & SSE 协议
网络·c++·websocket·网络协议·学习·面试
虎王物联3 天前
PHP Swoole实现物联网MQTT数据订阅与WebSocket实时推送
物联网·mqtt·websocket·php·swoole
一条泥憨鱼5 天前
【从0开始学习计算机网络】| WebSocket-握手、全双工和心跳
websocket·计算机网络·网络安全·https·dns
GitLqr5 天前
从 TCP 底层看实时通信:为什么 SSE 往往比 WebSocket 更香?
websocket·http·openai
脉动数据行情16 天前
Python WebSocket 国内商品期货|螺纹钢 & 铁矿石实时行情监听
开发语言·python·websocket
宠友信息6 天前
内容社区源码开发实践解析,用Spring Boot打造1:1仿小红书源码平台
java·spring boot·redis·websocket·mysql·spring·uni-app
limingade7 天前
智能拨号器APP-外部WebSocket话单推送系统接口文档
网络·websocket·智能拨号器app·远程推送号码到手机拨打电话·手机app稳定长连接·手机拨打电话后推送话单和录音
火云牌神7 天前
长连接与流式推送:规范 SSE / WebSocket 实现,替换无效轮询
websocket·网络协议·架构·ai编程·流式推送
脉动数据行情7 天前
Python WebSocket 实现融通金实时行情监听
开发语言·python·websocket