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() 钩子在组件销毁前断开连接。
要在Vue 3中使用Socket.io实现WebSocket连接,可以按照以下步骤进行: 1. 安装Socket.io客户端库 在Vue项目中使用npm或yarn安装Socket.io客户端库: ``` npm install socket.io-client ``` 或 ``` yarn add socket.io-client ``` 2.Vue组件中引入Socket.io客户端库 在需要使用WebSocketVue组件中引入Socket.io客户端库: ```javascript import io from 'socket.io-client' ``` 3. 创建WebSocket连接 在Vue组件的created()钩子函数中创建WebSocket连接: ```javascript created() { this.socket = io('http://localhost:3000') } ``` 这里我们使用localhost:3000作为示例,你需要将其更改为你实际使用WebSocket服务器地址。 4. 接收WebSocket消息 在Vue组件中,可以使用Socket.io提供的on()方法监听WebSocket消息: ```javascript created() { this.socket = io('http://localhost:3000') this.socket.on('message', message => { console.log(message) }) } ``` 这里我们监听了名为“message”的事件,你需要将其更改为你实际使用的事件名称。 5. 发送WebSocket消息 在Vue组件中发送WebSocket消息,可以使用Socket.io提供的emit()方法: ```javascript methods: { sendMessage() { this.socket.emit('message', 'Hello, WebSocket!') } } ``` 这里我们发送了一个名为“message”的消息,消息内容为“Hello, WebSocket!”,你需要将其更改为你实际使用的消息名称和内容。 以上就是使用Socket.ioVue 3中实现WebSocket连接的基本步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值