doc: make socket IPC examples more robust · nodejs/node@a0b3805

Original file line numberDiff line numberDiff line change

@@ -1052,8 +1052,9 @@ const { fork } = require('child_process');

10521052

const normal = fork('subprocess.js', ['normal']);

10531053

const special = fork('subprocess.js', ['special']);

10541054
1055-

// Open up the server and send sockets to child

1056-

const server = require('net').createServer();

1055+

// Open up the server and send sockets to child. Use pauseOnConnect to prevent

1056+

// the sockets from being read before they are sent to the child process.

1057+

const server = require('net').createServer({ pauseOnConnect: true });

10571058

server.on('connection', (socket) => {

10581059
10591060

// If this is special priority

@@ -1073,7 +1074,12 @@ passed to the event callback function:

10731074

```js

10741075

process.on('message', (m, socket) => {

10751076

if (m === 'socket') {

1076-

socket.end(`Request handled with ${process.argv[2]} priority`);

1077+

if (socket) {

1078+

// Check that the client socket exists.

1079+

// It is possible for the socket to be closed between the time it is

1080+

// sent and the time it is received in the child process.

1081+

socket.end(`Request handled with ${process.argv[2]} priority`);

1082+

}

10771083

}

10781084

});

10791085

```

@@ -1083,6 +1089,10 @@ tracking when the socket is destroyed. To indicate this, the `.connections`

10831089

property becomes `null`. It is recommended not to use `.maxConnections` when

10841090

this occurs.

10851091
1092+

It is also recommended that any `'message'` handlers in the child process

1093+

verify that `socket` exists, as the connection may have been closed during the

1094+

time it takes to send the connection to the child.

1095+
10861096

*Note: this function uses [`JSON.stringify()`][] internally to serialize the

10871097

`message`.*

10881098