search

Home  >  Q&A  >  body text

node.js - nodejs cluster中server是由谁创建的

简要代码如下:
if(cluster.isMaster){

   cluster.fork();
   cluster.fork();

}else{

http.createServer(function(){
    ...
}).bind(8080);

}
想问一下,为什么server的创建要写在else里面?那意思不就是 在子进程中创建server,运行了两次,就是创建了2个server?而且都是绑定的同样的端口号?求指点。

PHP中文网PHP中文网2787 days ago373

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 16:03:28

    This is how I understand it:
    When the file starts to be executed
    cluster.isMaster is true
    Then enter the true branch to fork
    Create a new thread for each fork. This thread will execute the file from the beginning
    At this time cluster.isMaster is false
    Enter false branch
    Execute to create the server
    As for why the same port is listened to
    In fact, only the main thread listens to this port
    cluster The main thread will implement the distributor
    distribute the request to other threads on this port

    reply
    0
  • 高洛峰

    高洛峰2017-04-17 16:03:28

    Created and listened to the port by the master process. When the request reaches the server master process, it accepts it and distributes it to the worker process

    reply
    0
  • Cancelreply