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>
相关推荐
安生生申9 小时前
MQTT 协议与 HTTP 协议的区别
网络·网络协议·http
一个程序员(●—●)13 小时前
HTTP基础介绍+OSI七层参考模型+HTTP协议介绍
网络·网络协议·http
派葛穆15 小时前
ESP32开发-作为TCP服务端接收数据
网络协议·tcp/ip
✿ ༺ ོIT技术༻18 小时前
Linux:深入理解数据链路层
linux·网络·网络协议
2501_9159214319 小时前
iOS HTTPS 抓包踩坑记:几种方案尝试与替代工具记录
websocket·网络协议·tcp/ip·http·网络安全·https·udp
林十一npc1 天前
Fiddler抓取APP端,HTTPS报错全解析及解决方案(一篇解决常见问题)
android·前端·网络协议·https·fiddler·接口测试
盛满暮色 风止何安1 天前
OSPF的路由
运维·服务器·网络·网络协议·网络安全·华为·智能路由器
郑文博Coding1 天前
WebSocket与Socket、TCP、HTTP的关系及区别
websocket·tcp/ip·http
小梦想的博客1 天前
后端接口请求http改为https
网络协议·http·https