vue项目中 socket.io 一直报错什么情况?
vue项目中 socket.io 一直报错什么情况?
今天做项目的时候有个网站的常见功能就是下载进度条,之前做过这方面的需求,就想看看怎么实现。起初我是想让让后台给一个接口,前端每隔一段时间就请求一下,但是这种方式也太常见了吧?后来问过其它人后,大佬说HTML5都出了websocket了,还在用Ajax去不断请求low不?然后我就学习了一下相关的webscoket的知识。
本文环境
web端:
- "vue": "^2.6.11"
- "vue-socket.io": "^3.0.10" (vue中socket.io插件)
- "socket.io-client": "^4.4.0" (socket.io-client端文件)
node server端:
- "koa": "^2.13.1"
- "socket.io": "^4.4.0" (socket.io 库)
本文实现效果
- web端用户点击按钮,将参数传给server端
- server端,接收参数,将结果执行遍历
- 遍历的同时将每一项,返回给前端 (如果数据很多或者每一次操作很耗时,就可以把当前执行到第几次了,计算出一个百分比,返回给web端,这就类似下载进度条的效果)
代码实现 (下面基本只展示socket相关的代码!!!)
vue-socket.io 和 socket.io 的使用请自行查看官方文档,本文就不CV了,vue 和 koa 快速搭建项目也不废话了,直接上socket代码。
web端:
main.js
文件
import VueSocketIO from "vue-socket.io"
import SocketIO from 'socket.io-client'
Vue.use(new VueSocketIO({
// debug: true,
connection: SocketIO('ws://localhost:3003', { //需要连接socket的地址
autoConnect: false //禁止自动连接socket,由于不需要一直连socket服务,所以这里设置关闭
}), //可以连接socket
options: {
transports: ['websocket', 'polling'] //socket.io的参数请看文档
}
}));
index.vue
文件(我还引入了elementUI,所以可以直接使用组件):
<template>
<el-container>
<el-main>
<el-row>
<el-col :span="24">
<div></div>
</el-col>
</el-row>
<el-row>
<el-col :span="24">
<div :id="uid" @click="start">点击连接webscokte服务</div>
</el-col>
</el-row>
</el-main>
</el-container>
</template>
<script>
export default {
name: 'Index',
data() {
return {
id:'',
uid:2,
num:0
};
},
mounted() {},
sockets: {
connect() {
this.id = this.$socket.id;
console.log('connect---监听socket连接状态', this.id);
},
disconnect(reason) {
console.log('disconnect--socket断开服务的原因:',reason);
},
message(data) { //监听message事件,方法是后台定义和提供的
console.log('message 接收到服务端传回的参数:',data );
this.num = data;
}
},
methods: {
// 执行socket服务
start(){
console.log('socket start Fn', this.$socket);
// 连接socket服务
this.$socket.connect();
// 触发server端的start事件
this.$socket.emit('start', this.uid);
}
}
};
</script>
<style lang="scss" scope>
</style>
node server端:
app.js
文件
// koa模块
const Koa = require('koa');
// http协议模块
const { createServer } = require("http");
// 实例化Koa模块
const app = new Koa();
const httpServer = createServer(app.callback());
// socket模块
const { Server } = require("socket.io");
// 为socket新起个端口
const io = new Server(3003, {
allowEIO3: true, //是否启用与 Socket.IO v2 客户端的兼容性。
transports: ['websocket', 'polling'],
cors: {
origin: "*",
methods: ["GET", "POST"]
}
});
io.on("connection", (socket) => {
console.log('connection socket连接成功');
socket.on('start', async (data)=>{ //监听start事件,web端会触发这个函数
let percentage = data*10;
console.log('server-client start fn', data, percentage);
for (let index = 0; index < percentage; index++) {
socket.emit('message', index); //触发web端的message事件
if (index==percentage) {
socket.disconnect(true); //执行完遍历,端开socket服务
console.log('socket.disconnect 关闭');
}
}
});
});
httpServer.listen(3000, () => {
console.log('starting at port 3000, http://localhost:3000/');
});
这样就写好代码了,把前后端服务开启器,在用户端打开控制台,点击页面就会看到参数了。
总结
vue-socket.io
中的connection
参数 最好使用socket.io-client
传入 (我一开始就没用,一直报错)- socket.io 默认是自动连接的,如果需要手动连接,可以在web端设置
autoConnect: false
- web端、server端,触发事件都是用的
emit
方式触发 - 多看文档,很多问题确实官方文档都写了,但是我还是一出问题就浮躁,没用仔细看文档,导致网上找了很多文章才解决。
- 本文例子非常简单易懂,希望对你有帮助!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2019-12-08 Markdown 基础语法
2019-12-08 VSCode常用插件之Simple New File使用
2019-12-08 Prettier - Code formatter使用
2019-12-08 VSCode常用插件之open in browser使用