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>
相关推荐
上海云盾-小余3 小时前
DDoS 攻击全解析:常见类型识别与分层防御思路
网络协议·tcp/ip·安全·ddos
不做菜鸟的网工4 小时前
H3C 本地 Portal + AAA 认证 模拟配置实验
网络协议
W.W.H.4 小时前
嵌入式常见的面试题1
linux·网络·经验分享·网络协议·tcp/ip
zmj3203244 小时前
CAN + 以太网 + Wi-Fi + BLE + TCP/IP + MQTT +HTTP协议层级
网络·网络协议·tcp/ip
发光小北5 小时前
IEC103 转 ModbusTCP 网关应用在什么场景?
网络·网络协议
BullSmall6 小时前
Prometheus 如何配置监控 SSL 证书即将过期
网络协议·ssl·prometheus
一只小鱼儿吖7 小时前
长效代理IP:构建稳定高效的网络数据通
网络·网络协议·tcp/ip
患得患失9498 小时前
【前端WebSocket】心跳功能,心跳重置策略、双向确认(Ping-Pong) 以及 指数退避算法(Exponential Backoff)
前端·websocket·算法
Vis-Lin8 小时前
BLE 协议栈:L2CAP 信道详解
网络·物联网·网络协议·蓝牙·iot·ble
北京耐用通信9 小时前
CC-Link IE转Modbus TCP集成实战:耐达讯自动化网关在五星级酒店节能改造中的应用
人工智能·物联网·网络协议·自动化·信息与通信