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() 钩子在组件销毁前断开连接。
相关推荐
2501_9159184112 小时前
多账号管理与自动化中的浏览器指纹对抗方案
websocket·网络协议·tcp/ip·http·网络安全·https·udp
Zhen (Evan) Wang1 天前
.NET 8 API 实现websocket,并在前端angular实现调用
前端·websocket·.net
zhangzuying10261 天前
在uni-app中实现类似文心一言的流式对话功能:从fetch到websocket的实践
websocket·uni-app·文心一言
xsh2192 天前
HTTP 和 WebSocket 的区别
websocket·网络协议·http
大G哥2 天前
【WebSocket&IndexedDB】node+WebSocket&IndexedDB开发简易聊天室
网络·websocket·网络协议
九班长3 天前
JMeter 中实现 双 WebSocket(双WS)连接
websocket·jmeter·proto
白露与泡影4 天前
聊聊四种实时通信技术:短轮询、长轮询、WebSocket 和 SSE
网络·websocket·网络协议
可儿·四系桜4 天前
WebSocket:实时通信的新时代
java·网络·websocket·网络协议
小芝麻咿呀4 天前
websocketd 10秒教程
websocket·web
2501_916013744 天前
从一次被抄袭经历谈起:iOS App 安全保护实战
websocket·网络协议·tcp/ip·http·网络安全·https·udp