安装依赖
npm install express socket.io
修改 package.json
"type": "module",
服务端代码
// server.js import express from "express"; import { createServer } from "http"; import { Server } from "socket.io"; import path from "path"; const __dirname = path.resolve(); const app = express(); const server = createServer(app); const io = new Server(server); // http app.get("/", (req, res) => { res.sendFile(__dirname + "/index.html"); }); // websocket io.on("connection", (client) => { console.log("socket connection"); // 消息发送 client.on("chat message", (msg) => { io.emit("chat message", msg); }); // 断开连接 client.on("disconnect", () => { console.log("socket disconnect"); }); }); server.listen(3000, () => { console.log("server start"); });
客户端代码
<!-- index.html --> <!-- 消息输入 --> <form id="form"> <input id="input" type="text" /> <button>发送</button> </form> <!-- 消息显示 --> <div id="message-list"></div> <script src="socket.io/socket.io.js"></script> <script> const form = document.querySelector("#form"); const input = document.querySelector("#input"); const messageList = document.querySelector("#message-list"); const socket = io(); // 发送消息 form.addEventListener("submit", function (event) { event.preventDefault(); if (input.value) { socket.emit("chat message", input.value); input.value = ""; } }); // 接收消息 socket.on("chat message", (msg) => { const li = document.createElement("li"); li.textContent = msg; messageList.appendChild(li); }); </script>