net.Server.listenFD()
API. I hope this code will be a good example of how easy it is to load multiple server cores by combining the transfer of file descriptors and Web Workers.
- var path = require ( 'path' ) ;
- var netBindings = process. binding ( 'net' ) ;
- var Worker = require ( 'webworker' ) . Worker ;
- var fd = netBindings. socket ( 'tcp4' ) ;
- netBindings. bind ( fd , 8080 ) ;
- netBindings. listen ( fd , 128 ) ;
- for ( var i = 0 ; i < 3 ; i ++ ) {
- var w = new Worker ( path. join ( __dirname , 'worker.js' ) ) ;
- w. postMessage ( { 'banner' : 'Hello, world!' } , fd ) ;
- }
listen()
. Instead, we expect to receive messages from the parent process. When an event is received, we retrieve the file descriptor from the message and use it to bind our http.Server instance to the socket. As soon as http.Server.listenFD()
is called, this process will start processing requests.
- var assert = require ( 'assert' ) ;
- var http = require ( 'http' ) ;
- var banner = undefined ;
- var srv = http. createServer ( function ( req , resp ) {
- resp. writeHead ( 200 , { 'Content-Type' : 'text / plain' } ) ;
- resp. write ( banner + '(pid' + process. pid + ') \ n ' ) ;
- resp. end ( ) ;
- } ) ;
- onmessage = function ( msg ) {
- assert. ok ( msg. fd && msg. fd > 0 ) ;
- banner = msg. data . banner ;
- srv. listenFD ( msg. fd ) ;
- } ;
- % curl 'http: // localhost: 8080'
- Hello, world! (pid 27727)
- % curl 'http: // localhost: 8080'
- Hello, world! (pid 27728)
- % curl 'http: // localhost: 8080'
- Hello, world! (pid 27729)
- % curl 'http: // localhost: 8080'
- Hello, world! (pid 27727)
Source: https://habr.com/ru/post/95972/