如何搭建一个 websocket
环境:
- NodeJs
- socket.io 4.7.2
安装依赖
yarn add socket.io
创建服务器
引入文件
特别注意: 涉及到 colors 的代码,请采取 console.log()
打印
// 基础老三样
import http from "http";
import fs from "fs";
import { Server } from "socket.io";
// 下面2个是我本地开发的,你们可能没有
import colors from "colors-console";
import constant_color from "./colors.js";
createServer
请在当前目录下创建 index.html 文件。【客户端需要连接 socket.io】
<script src="/socket.io/socket.io.js"></script>
<script>
constsocket = io();
</script>
服务端代码:
const server = http.createServer((req, res) => {
fs.readFile("./index.html", "utf-8", (err, data) => {
if (err) {
res.writeHead(500, "utf-8", e);
res.end();
}
res.writeHead(200, {
"Content-Type": "text/html"
});
res.end(data, "utf-8");
});
});
websocket
简单判断客户端是否连接,断开。
const io = new Server(server);
io.on("connection", socket => {
console.succ("User connected.");
// 用户断开连接
socket.on("disconnect", () => {
console.err("User disconnected.");
})
});
server.listen(3000, "127.0.0.1");
启动服务器
yarn app
附录
再次提醒: 请去除所有 console.err console.succ colors 等有关颜色内容
项目结构:【它们都是同级目录,最顶层】
D:.
│ app.js
│ colors.js
│ index.html
│ package.json
│ yarn.lock
│
└─node_modules
app.js 代码:
import http from "http";
import fs from "fs";
import { Server } from "socket.io";
import colors from "colors-console";
import constant_color from "./colors.js";
// 重写 console.err
console.err = (...msg) => {
let str = "";
for (let i = 0; i < msg.length; i++) {
str += msg[i] + " ";
}
console.log(colors(constant_color.red, str));
}
// 定义 console.succ
console.succ = (...msg) => {
let str = "";
for (let i = 0; i < msg.length; i++) {
str += msg[i] + " ";
}
console.log(colors(constant_color.green, str));
}
const server = http.createServer((req, res) => {
fs.readFile("./index.html", "utf-8", (err, data) => {
if (err) {
res.writeHead(500, "utf-8", e);
res.end();
}
res.writeHead(200, {
"Content-Type": "text/html"
});
res.end(data, "utf-8");
});
});
const io = new Server(server);
io.on("connection", socket => {
console.succ("User connected.");
// 用户断开连接
socket.on("disconnect", () => {
console.err("User disconnected.");
})
});
server.listen(3000, "127.0.0.1");
console.log("Server running at x1B[36mx1B[4mhttp://127.0.0.1:3000x1B[0m");
index.html 代码:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<h1>Hello Friend! ?</h1>
<script>
const socket = io();
</script>
</body>
</html>