在Node.js中,你可以使用内置的HTTP模块或第三方库(如Express)来创建Web服务器并处理并发连接。要查看并发连接,你可以监听服务器的connection
事件,并在每次有新的连接时递增一个计数器。同时,你还需要监听close
事件来递减计数器。这样,你就可以实时了解服务器的并发连接数。
以下是一个使用HTTP模块的示例:
const http = require('http');
let concurrentConnections = 0;
const server = http.createServer((req, res) => {
concurrentConnections++;
console.log(`当前并发连接数: ${concurrentConnections}`);
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
});
server.on('connection', () => {
console.log('新的连接');
});
server.on('close', () => {
concurrentConnections--;
console.log(`当前并发连接数: ${concurrentConnections}`);
});
server.listen(3000, () => {
console.log('服务器运行在 http://localhost:3000');
});
如果你使用的是Express框架,可以这样做:
const express = require('express');
const app = express();
let concurrentConnections = 0;
app.use((req, res, next) => {
concurrentConnections++;
console.log(`当前并发连接数: ${concurrentConnections}`);
next();
});
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.on('connection', () => {
console.log('新的连接');
});
app.on('close', () => {
concurrentConnections--;
console.log(`当前并发连接数: ${concurrentConnections}`);
});
app.listen(3000, () => {
console.log('服务器运行在 http://localhost:3000');
});
请注意,这些示例仅用于演示目的,实际生产环境中可能需要更复杂的处理和优化。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: Ubuntu系统如何卸载FileZilla