• 如何搭建一个 websocket


    环境:

    • NodeJs
    • socket.io 4.7.2

    安装依赖

    yarn add socket.io
    
    • 1

    创建服务器

    引入文件

    特别注意: 涉及到 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";
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    createServer

    请在当前目录下创建 index.html 文件。【客户端需要连接 socket.io】

    <script src="/socket.io/socket.io.js">script>
    
    <script>
        constsocket = io();
    script>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    服务端代码:

    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");
        });
    });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    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");
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    启动服务器

    yarn app
    
    • 1

    在这里插入图片描述

    附录

    再次提醒: 请去除所有 console.err console.succ colors 等有关颜色内容
    在这里插入图片描述
    项目结构:【它们都是同级目录,最顶层】

    D:.
    │  app.js
    │  colors.js
    │  index.html
    │  package.json
    │  yarn.lock
    │
    └─node_modules
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    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[36m\x1B[4mhttp://127.0.0.1:3000\x1B[0m");
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51

    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>Documenttitle>
        <script src="/socket.io/socket.io.js">script>
    head>
    
    <body>
        <h1>Hello Friend! 😀h1>
    
        <script>
            const socket = io();
        script>
    body>
    
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
  • 相关阅读:
    教资认定报名照片要求小于190kb…
    解决mac pro 连接4k显示器严重发烫、卡顿问题
    Hyperf基础使用
    关于JavaScript关键字之一this解读
    嵌入式养成计划-42----QT 创建项目--窗口界面--常用类及组件
    html实现9*9乘法表
    Java设计模式之抽象工厂模式
    高级Android开发工程师
    MVVM模式根模块
    架构设计的课程资料
  • 原文地址:https://blog.csdn.net/qq_56402474/article/details/133608225