app.js
const express = require('express')
const app = express()
app.get('/', (req, res) => {
console.log(`(进程${process.pid})-- get request`)
res.send('Hello world')
})
module.exports = app
udpServer.js
const dgram = require('dgram')
const udpServer = dgram.createSocket('udp4')
udpServer.on('message', (msg, rinfo) => {
console.log(`(进程${process.pid})-- 服务器接收到来自 ${rinfo.address}:${rinfo.port} 的 ${msg}`);
})
udpServer.on('listening', () => {
const address = udpServer.address();
console.log(`(进程${process.pid})-- 服务器监听 ${address.address}:${address.port}`);
});
module.exports = udpServer
index.js
const app = require('./app')
const udpServer = require('./udpServer')
const cluster = require('cluster')
const numCPUs = require('os').cpus().length
const HTTP_PORT = 3003
const UDP_PORT = 9999
// app.listen(HTTP_PORT, () => {
// console.log(`HTTP listening ${HTTP_PORT}`)
// })
// udpServer.bind(UDP_PORT)
/**
* 集群
*/
if (cluster.isMaster) {
console.log(`主进程 ${process.pid} 正在运行`);
// 衍生工作进程。
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
} else {
app.listen(HTTP_PORT, () => {
console.log(`(进程${process.pid})-- HTTP listening ${HTTP_PORT}`)
})
udpServer.bind(UDP_PORT)
console.log(`工作进程 ${process.pid} 已启动`);
}
运行结果
运行结果.png
网友评论