多节点应用程序如何重用端口

时间:2018-12-27 19:57:19

标签: node.js

当我在Java应用程序(example)中运行多次使用OS端口的同一应用程序时,出现以下异常。

    Exception in thread "main" java.net.BindException: Address already in use
        at sun.nio.ch.Net.bind0(Native Method)
        at sun.nio.ch.Net.bind(Net.java:433)
        at sun.nio.ch.Net.bind(Net.java:425)
        at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:223)

node_cluster.js

    const cluster = require('cluster'),
        cpus = require('os').cpus().length;

    cluster.setupMaster({
        exec: '3_worker.js'
    });

    if(cluster.isMaster) {
        for(let i = 0; i< cpus; i++) {
            cluster.fork();
        }
        cluster.on('fork', worker => console.log(worker.id + " is forked"));
        cluster.on('listening', (worker, address) => console.log(worker.id + "is listening on " + JSON.stringify(address)));
        cluster.on('online', worker => console.log(`${worker.id} is online`));
        cluster.on('disconnect', worker => console.log(`${worker.id} is disconnected`));
        cluster.on('exit', (worker, code, signal) => console.log(`${worker.id} is dead due to ${code} and ${signal}`));
    }

3_worker.js

    const http = require('http');

    http.createServer((req, res) => {
        console.log(req.url);
        res.writeHead(200);
        res.end('hello');
    }).listen(8080);

以上程序返回结果-

    3is listening on {"addressType":4,"address":null,"port":8080}
    5is listening on {"addressType":4,"address":null,"port":8080}
    4is listening on {"addressType":4,"address":null,"port":8080}
    7is listening on {"addressType":4,"address":null,"port":8080}
    8is listening on {"addressType":4,"address":null,"port":8080}
    2is listening on {"addressType":4,"address":null,"port":8080}
    1is listening on {"addressType":4,"address":null,"port":8080}
    6is listening on {"addressType":4,"address":null,"port":8080}

ps的输出为-

    $ ps
    PID TTY           TIME CMD
    4477 ttys001    0:00.16 /bin/bash -l
    5219 ttys001    0:00.12 node 3_clustering.js
    5220 ttys001    0:00.14 /Users/rajkumar.natarajan/.nvm/versions/node/v8.15.0/b
    5221 ttys001    0:00.14 /Users/rajkumar.natarajan/.nvm/versions/node/v8.15.0/b
    5222 ttys001    0:00.13 /Users/rajkumar.natarajan/.nvm/versions/node/v8.15.0/b
    5223 ttys001    0:00.14 /Users/rajkumar.natarajan/.nvm/versions/node/v8.15.0/b
    5224 ttys001    0:00.14 /Users/rajkumar.natarajan/.nvm/versions/node/v8.15.0/b
    5225 ttys001    0:00.14 /Users/rajkumar.natarajan/.nvm/versions/node/v8.15.0/b
    5226 ttys001    0:00.14 /Users/rajkumar.natarajan/.nvm/versions/node/v8.15.0/b
    5227 ttys001    0:00.14 /Users/rajkumar.natarajan/.nvm/versions/node/v8.15.0/b
    5794 ttys002    0:00.05 /bin/bash --rcfile /Applications/IntelliJ IDEA.app/Con
    6063 ttys003    0:00.03 /Applications/Utilities/iTerm.app/Contents/MacOS/iTerm
    6065 ttys003    0:00.04 -bash

多个node.js进程如何能够在同一端口上侦听。

1 个答案:

答案 0 :(得分:2)

只有主机打开了端口。它处理端口上的所有传入和传出流量,并将流量分流到辅助线程进行处理。