express 怎么搭建 WebSocket 服务器

一:使用 express-ws

javascript 复制代码
var express = require('express');
var app = express();
var expressWs = require('express-ws')(app);

app.use(function (req, res, next) {
  console.log('middleware');
  req.testing = 'testing';
  return next();
});

app.get('/', function(req, res, next){
  console.log('get route', req.testing);
  res.end();
});

app.ws('/path', function(ws, req) {
  console.log('socket', req.testing);
  ws.on('message', function(msg) {
    console.log('message', msg);
    ws.send(msg);
  });
});

app.listen(3000);

客户端

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket Example</title>
</head>
<body>
    <script>
        const ws = new WebSocket('ws://localhost:3000/path');

        ws.onopen = () => {
            console.log('Connected to the server');
            ws.send('Hello Server!');
        };

        ws.onmessage = (event) => {
            console.log(`Message from server: ${event.data}`);
        };

        ws.onclose = () => {
            console.log('Disconnected from the server');
        };
    </script>
</body>
</html>

二:使用 Socket.IO

javascript 复制代码
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');

const app = express();
const server = http.createServer(app);

const io = socketIo(server, {
    path: '/path', // 设置Socket.IO的路径
    cors: {
      origin: "*"
    }
});

io.on('connection', (socket) => {
    console.log('New client connected');
    
    socket.on('message', (message) => {
        console.log(`Received message => ${message}`);
        
        // Broadcast the message to all clients
        io.emit('message', `Server: ${message}`);
    });

    socket.on('disconnect', () => {
        console.log('Client disconnected');
    });
});

server.listen(3000, () => {
    console.log('Server is listening on port 3000');
});

客户端:

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Socket.IO Example</title>
    <script src="https://cdn.socket.io/4.7.5/socket.io.min.js" integrity="sha384-2huaZvOR9iDzHqslqwpR87isEmrfxqyWOF7hr7BY6KG0+hVKLoEXMPUJw3ynWuhO" crossorigin="anonymous"></script>
</head>
<body>
    <script>
        const socket = io('http://localhost:3000', {
          path: '/path'
        });

        socket.on('connect', () => {
            console.log('Connected to the server');
            socket.send('Hello Server!');
        });

        socket.on('message', (message) => {
            console.log(`Message from server: ${message}`);
        });

        socket.on('disconnect', () => {
            console.log('Disconnected from the server');
        });
    </script>
</body>
</html>
相关推荐
阿巴~阿巴~12 分钟前
自定义协议设计与实践:从协议必要性到JSON流式处理
服务器·网络·网络协议·json·操作系统·自定义协议
jinxinyuuuus7 小时前
GTA 风格 AI 生成器:跨IP融合中的“视觉语义冲突”与风格适配损失
人工智能·网络协议
嵌入式-小王8 小时前
每天掌握一个网络协议----ICMP
网络·网络协议·ping
Awkwardx8 小时前
Linux网络编程—应用层协议HTTP
网络·网络协议·http
Running_slave10 小时前
你应该了解的TCP滑窗
前端·网络协议·tcp/ip
无证驾驶梁嗖嗖12 小时前
无需公网 IP,MongoDB 也能跨环境访问?试试这个实用方案
网络协议·tcp/ip·mongodb
Mu.38712 小时前
计算机网络模型
网络·网络协议·计算机网络·安全·http·https
D***y20114 小时前
使用Node.js搭配express框架快速构建后端业务接口模块Demo
node.js·express
飞行增长手记1 天前
什么是高匿代理IP?安全吗?怎么选?
网络协议·tcp/ip·安全
上海云盾安全满满1 天前
高防 IP 是如何帮助数藏行业防刷
网络·网络协议·tcp/ip