当前位置: 首页 > news >正文

Vue3+socket.io 项目本地vite配置

进行websocket项目开发时,常用到 socket.io 这个库。

前端使用 vite7 进行 Vue3 项目开发时,下面记录相关内容。

前端项目

# 项目搭建
pnpm create vite# 安装依赖
pnpm add socket.io-client

客户端代码

import { io } from "socket.io-client";const socket = io()export default socket;

vite.config.ts 配置文件

import path from "path"
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'// https://vite.dev/config/
export default defineConfig({plugins: [vue()],resolve: {alias: {"@": path.resolve(__dirname, './src'),}},server: {proxy: {// socket代理地址配置'/socket.io': {target: 'http://localhost:3000',ws: true,rewriteWsOrigin: true,},}}
})

后端项目

node.js项目 server.js 相关代码

const Koa = require("koa")
const http = require("http")
const fs = require("fs")
const path = require("path")
const { Server } = require("socket.io")const app = new Koa()
const server = http.createServer(app.callback())
const io = new Server(server)app.use(async (ctx, next) => {const { method, url } = ctxif (method === "GET" && url === "/") {ctx.type = "text/html"ctx.body = fs.createReadStream(path.join(__dirname, "public", "index.html"))} else if (method === "GET" && url.startsWith("/public/")) {const filePath = path.join(__dirname, url)try {ctx.type = url.endsWith(".css") ? "text/css" : url.endsWith(".js") ? "application/javascript" : "text/plain"ctx.body = fs.createReadStream(filePath)} catch (err) {ctx.status = 404}} else {await next()}
})io.on("connection", (socket) => {console.log(`客户端已连接: ${socket.id}`)console.log("a user connected")// 接收客户端发送的消息socket.on("message", (msg) => {console.log("收到消息:", msg)// 广播给所有客户端(包括发送者)io.emit("message", msg)})
})server.listen(3000, () => {console.log("server running at http://localhost:3000")
})

后端项目启动

node server.js

我们本地启动了node.js的后台服务后,前端就可以进行调试了。

http://www.dtcms.com/a/465349.html

相关文章:

  • wangEditor
  • Unity网络开发--超文本传输协议Http(1)
  • 从“用框架”到“控系统”——数据流、事件流、接口边界是如何形成的;
  • 有没有什么网站做泰国的东西做网站排名软件
  • 达梦数据库逻辑备份与还原
  • 如何解决Redis和数据库的一致性问题?
  • 新版saas餐饮外卖小程序源码/微信/支付宝/抖音/扫码点餐/DIY装修/美团代付/全开源
  • react 修复403页面无法在首页跳转问题
  • 学子网站建设郑州门户网站建设哪家好
  • 新乡网站优化公司看市场行情用什么软件
  • SQL注入原理与方法
  • 如何将Vue 项目转换为 Android App(使用Capacitor)
  • 输出端口原理图分析
  • 响应式网站建设有利于seo常熟做网站公司
  • php购物网站开发设计免费网站软件app
  • CTF攻防世界WEB精选基础入门:disabled_button
  • 昂瑞微:引领射频前端国产化浪潮,铸就5G时代核心竞争力
  • 基于SpringBoot的高校教师科研项目信息管理系统
  • 富文本返回的Html数据格式化
  • 昂瑞微冲刺科创板:创新驱动,引领射频芯片国产化新征程
  • 基于Java(Spring Boot)+MySQL实现电商网站
  • 记录一次生产环境数据库死锁的处理过程
  • 首先确定网站建设的功能定位seo推广工具
  • Nestjs框架: Pino 与 Pino-Elasticsearch 组合实现高性能日志写入与检索的完整方案
  • 走近实验技术中的“四大发明”之Southern blot、Northern blot和Western blot
  • 网站建设需求文档模板下载想做电商从哪里入手
  • ai做网站建站做得好的公司
  • 网络层--数据链路层
  • 网站设计应该遵循哪些原则手机网站打开手机app
  • 【AI安全】Qwen3Guard: 实时流式检测实现AI模型安全防护新标杆