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>
相关推荐
while(1){yan}5 小时前
网络协议TCP
java·网络·网络协议·tcp/ip·青少年编程·电脑常识
yBmZlQzJ5 小时前
财运到内网穿透-群晖NAS安装(docker版本)
运维·经验分享·网络协议·docker·容器
tiantianuser5 小时前
RDMA设计15:连接管理模块设计2
网络协议·fpga开发·rdma·高速传输·cmac
阿里云云原生6 小时前
LoongSuite:解决 WebSocket 全链路可观测性难题,赋能 AI 应用的实时链路追踪
人工智能·websocket·网络协议·阿里云·云原生·可观测
李少兄7 小时前
从零开始全面掌握 HTTPS
网络协议·http·https
福尔摩斯张7 小时前
TCP协议深度解析:从报文格式到连接管理(超详细)
linux·c语言·网络·c++·笔记·网络协议·tcp/ip
游戏开发爱好者87 小时前
HTTPS DDoS 排查 异常流量到抓包分析
网络协议·ios·小程序·https·uni-app·iphone·ddos
JXNL@8 小时前
网通领域核心设备解析:CPE、IP Phone 与 AP 技术全指南
网络·网络协议·tcp/ip
博语小屋8 小时前
Socket UDP 网络编程V2 版本- 简单聊天室
linux·网络·c++·网络协议·udp
..空空的人9 小时前
C++基于protobuf实现仿RabbitMQ消息队列---技术认识2
服务器·数据库·c++·网络协议·gtest·异步·protobuf