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>
相关推荐
gihigo19986 分钟前
基于TCP协议实现视频采集与通信
网络协议·tcp/ip·音视频
白太岁4 小时前
通信:(5) 电路交换、报文交换与分组交换
运维·服务器·网络·网络协议
小扎仙森5 小时前
关于阿里云实时语音翻译-Gummy推送WebSocket
websocket·阿里云·云计算
EasyGBS5 小时前
国标安全升级:GB28181平台EasyGBS支持GB35114协议的应用场景与核心优势
网络协议·安全·gb28181·gb35114
凯酱6 小时前
Windows防火墙入站规则IP白名单
windows·网络协议·tcp/ip
稻草猫.7 小时前
TCP与UDP:传输层协议深度解析
笔记·后端·网络协议
科技块儿8 小时前
如何用离线库秒筛“数据中心”IP段并自动封号?
网络·网络协议·tcp/ip
上海云盾第一敬业销售8 小时前
选择最佳高防CDN与高防IP服务以保证网站安全
网络协议·tcp/ip·安全
傻啦嘿哟8 小时前
免费代理IP获取与验证:实战爬取代理网站并筛选可用IP
网络·网络协议·tcp/ip
上海云盾-小余9 小时前
高防IP与传统防护的互补性分析
网络·网络协议·tcp/ip