vue使用socket.io

Karle / 2023-09-06 / 原文

Vue 项目使用socket.io

使用library socket.io-client 或者 vue-socket.io

npm install socket.io-client ||
npm install vue-socket.io

使用socket.io-client

socket.io-clientsocket.io原配插件

  • 在对应的组件内使用
import { io } from 'socket.io-client'
this.socket = io(socketUrl, {transports: ['websocket']})
  • 由于transports默认配置为polling,因此需要手动设置为websocket,将长轮询改变为websocket

使用vue-socket.io

在main.js中进行配置

import VueSocketIO from 'vue-socket.io'
Vue.use(
  new SocketIO({
    debug: true, 
    connection:'http://localhost:3001',
    options:{
      autoConnect: false,
      path: "/my-app/",
      transports: ['websocket'],
      extraHeaders:{},
    },
  })
)

第二种较第一种复杂,不推荐使用