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>
相关推荐
一颗青果5 分钟前
HTTP协议详解
linux·网络·网络协议·http
晚枫歌F8 小时前
TCP协议详解
网络·网络协议·tcp/ip
秋4278 小时前
防火墙基本介绍与使用
linux·网络协议·安全·网络安全·架构·系统安全
sweet丶8 小时前
扩展了解DNS放大攻击:原理、影响与防御
网络协议·安全
科技块儿10 小时前
我应该如何选择并使用IP数据库评估不同地区的定位精度(⊙_⊙?)
网络·网络协议·tcp/ip
万粉变现经纪人11 小时前
如何解决 pip install SSL 报错 ValueError: check_hostname requires server_hostname 问题
网络·python·网络协议·beautifulsoup·bug·ssl·pip
松涛和鸣12 小时前
DAY42 SQLite3 : Dictionary Import and Data Query Implementation with C Language
linux·c语言·数据库·单片机·网络协议·sqlite
小新11015 小时前
vscode+nodejs+express 搭建一个简单网站
vscode·node.js·express
Channon_15 小时前
双网卡绑定、软PRP、硬PRP技术解析:区别与联系
物联网·网络协议·可用性测试
仰科网关16 小时前
化工厂SCADA系统OPC DA数据转Modbus TCP接入全厂监控平台项目案例
网络·网络协议·modbus·snmp·opc da·协议转换