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>
相关推荐
FPGA_Linuxer2 天前
FPGA 40 DAC线缆和光模块带光纤实现40G UDP差异
网络协议·fpga开发·udp
real 12 天前
传输层协议UDP
网络·网络协议·udp
hsjkdhs3 天前
网络编程之UDP广播与粘包问题
网络·网络协议·udp
AD钙奶-lalala3 天前
SpringBoot实现WebSocket服务端
spring boot·后端·websocket
yzx9910133 天前
接口协议全解析:从HTTP到gRPC,如何选择适合你的通信方案?
网络·人工智能·网络协议·flask·pygame
板鸭〈小号〉3 天前
UDP-Server(3)chat聊天室
网络·网络协议·udp
weixin_456904273 天前
使用HTTPS 服务在浏览器端使用摄像头的方式解析
网络协议·http·https
疯狂的维修3 天前
关于Gateway configration studio软件配置网关
网络协议·c#·自动化·gateway
wow_DG3 天前
【WebSocket✨】入门之旅(五):WebSocket 的安全性
网络·websocket·网络协议
往事随风去3 天前
别再纠结了!IM场景下WebSocket和MQTT的正确选择姿势,一文讲透!
后端·websocket·架构