Vue项目中使用socket通信(vue-socket.io)

  • vue-socket.io 其实是在 socket.io-client(在浏览器和服务器之间实现实时、双向和基于事件的通信) 基础上做了一层封装,将 $socket 挂载到 vue 实例上,同时可使用 sockets 对象轻松实现组件化的事件监听,在 vue 项目中使用起来更方便。
  • 官方文档

基本使用:

前端Vue

  1. 安装(这里我们安装vue.socket.io模块和socket.io-client模块,也可以不用socket.io-client模块,请往下看。)
npm i vue-socket.io
npm i socket.io-client
  1. Vue项目中的main.js中引入(使用socket.io-client连接)
// main.js
import Vue from 'vue'
import store from './store'
import App from './App.vue'
import VueSocketIO from 'vue-socket.io' // 引入vue-socket.io
import SocketIO from "socket.io-client" // 引入socket.io-client

Vue.config.productionTip = false //关闭Vue生产提示

// 设置socket 连接参数
const socketOptions = {
autoConnect: false, // 关闭Vue实例创建自动连接 (指定情况下才连接socket服务器)
}

// 全局挂载vue-socket.io实例
Vue.use( //设置VueSocketIO
new VueSocketIO({
debug: true, // debug调试,生产建议关闭自动连接
// 设置连接的服务端地址(这里是动态,因为我的项目需要), 同时使用socket连接参数关闭
connection: SocketIO(`http://127.0.0.1:3000?token=${localStorage.getItem('token')}`,socketOptions),
extraHeaders: {
'Access-Control-Allow-Credentials': true //允许所有跨域
},
})
)

// 全局创建Vue实例
new Vue({
router,// 全局挂载路由
store,// 创建全局仓库
render: h => h(App),
watch:{
'$store.state.userInfo.id'(newVal, oldVal){
if(newVal){//监视登录的用户id,一旦用户登陆成功,开始连接后端的socket服务器
this.$socket.open() // 手动连接socket服务器
this.sockets.subscribe('监听的事件字段',data=>{
console.log('输出后端转发过来的消息')
})
}
}
},
beforeDestroy () {// Vue实例销毁时自动关闭连接
this.$socket.close()//关闭socket连接
}

}).$mount('#app')

WebSocket 事件官方文档

事件 事件处理程序 描述
open Socket.onopen -> (this.$socket.open()) 连接建立时触发(手动建立)
message Socket.onmessage -> (this.$socket.message()) 客户端接收服务端数据时触发
error Socket.onerror -> (this.$socket.error()) 通信发生错误时触发
close Socket.onclose -> (this.$socket.close()) 连接关闭时触发(手动关闭)

在组件中使用

  • 在组件中使用vue-socket.io订阅事件以及监听事件案例
<template>
<div id="app">
<div id="nav">
<button @click="connect">连接socket</button>
<button @click="sendMessage">发送数据</button>
</div>
</div>
</template>

<script>
export default {
sockets:{ // 设置监听事件(自定义或者内置事件)
connecting () { // 内置事件(正在连接)
console.log("Socket 正在连接");
},
disconnect () { // 内置事件(断开连接)
alert("Socket 断开");
},
connect_error () { // 内置事件(连接错误)
console.log("Socket 连接失败");
},
connect () { // 内置事件(连接完成)
console.log("Socket 连接成功");
},
welcome: data => { // 自定义事件
console.log('welcome data ', data)
}
},

methods:{
// 连接socket
connect() {
this.$socket.open()// 开始连接socket
// 订阅事件
this.sockets.subscribe('welcome', data => {
console.log('welcome data ', data)
})

},
// 发送消息
sendMessage() {
this.$socket.emit('hello', '这里是客户端')
}
},
}
</script>

服务端(node)

/* ---------------- 服务端 ------------------ */
const express = require('express')
// 创建服务器
const app = express()
const http = require('http').Server(app) // 使用http模块将后端服务器与socket服务器结合在一起
var cors = require('cors')
app.use(cors())//使用跨域模块

// 使用http模块将后端服务器与socket服务器结合在一起
const io = require('socket.io')(http, {
cors: {
origin: '*',//允许全世界跨域
methods: ['GET', 'POST'],
credentials: true,
allowEIO3: true
},
transport: ['websocket']
})

// 启动socket.io监听事件模块
io.on('connection', function (socket) {
console.log('有用户连接到该socket服务器了')

socket.on('disconnect', function () {
console.log('有用户断开连接了~')
})

socket.on('监听的事件字段', function (data) {// 可以使用箭头函数
console.log('传过来的消息数据',data)
// send data
socket.emit('发送消息字段', {// 做消息的转发
msg: data,
})
})
})

/* ------------------------------ 启动服务器 --------------------------------------- */
http.listen(3000,()=>{
console.log(`服务器已启动! 3000端口号正在监听......`);
})


结果展示:

image