前言: 前端自己架起服务器 给自己造点东西玩玩吧
1.搭建起服务(node.js)
下载依赖
npm i socket.io cors
const http = require("http"); const express = require("express"); const app = express(); const cors = require("cors"); let timer = null; // 创建一个HTTP服务器 const server = http.createServer(app); const io = require("socket.io")(server); // 配置 app.use(express.urlencoded({ extended: false })); app.use(express.json()); app.use(express.static("./public")); app.use(cors()); // 监听连接事件 io.on("connection", (socket) => { console.log("一个用户链接了"); // 发送欢迎消息给新连接的客户端 // 定时发送心跳 timer = setInterval(() => { // socket.emit('heartbeat'); console.log("Welcome to the server!"); socket.emit("message", "Welcome to the server!"); }, 3000); // socket.emit("message", "Welcome to the server!"); socket.on("test", (data) => { console.log("test:", data); // 在收到foo事件后,向客户端发送一个bar事件 socket.emit("test", "收到test消息了!!"); }); // 监听断开连接事件 socket.on("disconnect", () => { console.log("断开链接了"); clearInterval(timer); timer = null; }); // 监听客户端发送的foo事件 socket.on("foo", (data) => { console.log("Foo event received:", data); // 在收到foo事件后,向客户端发送一个bar事件 socket.emit("bar", "Hello from the server!"); }); }); // 在服务器关闭时清除所有定时器 function clearTimers() { clearInterval(timer); } // 监听服务器关闭事件 server.on('close', () => { console.log('Server is closing'); clearTimers(); }); server.listen("8010", () => { console.log("8010端口启动"); });
nodemon .app.js 运行起来就行了 至于想传 数据 自己整就行了
2.前端内容 (vite+vue3)
npm i socket.io-client
1.在src根目录下面建起socket.js文件夹
import { reactive } from "vue"; import { io } from "socket.io-client"; export const state = reactive({ num:1, connected: true, fooEvents: [], barEvents: [], }); // 下面自己根据环境的判断 给地址就行了 const URL = process.env.NODE_ENV === "production"? "http://localhost:8010": "http://localhost:8010"; export const socket = io(URL, { query: {}, transports: ["websocket", "polling"], connected: state.connected, // 是否自动重连 reconnectionAttempts: 3, // 重连尝试次数 reconnectionDelay: 1000, // 重连延迟时间(毫秒) reconnectionDelayMax: 5000, // 最大重连延迟时间(毫秒) pingTimeout: 5000, // 5秒未收到 'pong' 则认为连接断开 pingInterval: 2000, // 2秒发送一次心跳 pingMsg: 'custom-ping', // 使用自定义的心跳消息 }); socket.on("connect", () => { // socket.on("connection", () => { state.connected = true; console.log("链接成功"); }); socket.on("disconnect", () => { state.connected = false; }); socket.on("bar", (...args) => { state.barEvents.push(args); }); // 监听来自服务器的消息事件 socket.on('message', (message) => { // 处理收到的消息,例如将其显示在页面上 console.log('收到消息:', message); });
2.在需要用到socket的组件 引入就行了
<script setup> import { watch,ref,onUnmounted, computed, onMounted } from 'vue' import { state, socket } from "@/socket.js"; defineProps({ msg: String, }) // console.log(state,'state'); const connected = computed(() => { return state.num }) const count = ref(0) const addone = ()=>{ state.num +=1; console.log(state,'state'); } watch(()=>state.num,(newval,oldval)=>{ console.log(newval,oldval,'newval'); socket.emit('test',newval) },{deep:true}) onMounted(() => { // console.log(socket, 'socket'); socket.on(); }) onUnmounted(() => { // 在组件销毁时取消注册 Socket.IO 监听器 socket.off("connect"); socket.off("disconnect"); socket.off("foo"); socket.off("bar"); socket.off("message"); }); </script> <template> <h1>State: {{ connected }}</h1> <button @click="addone">num +1</button> </template> <style scoped> .read-the-docs { color: #888; } </style>