Dane Springmeyer
@springmeyer
Basics of message passing in Node.js
Goals
-
Understand tools for IPC (inter-process communication)
-
Build awareness of high perf designs for cpu-bound apps
-
Hint at advanced, emerging topics around multi-core Node
Topics
-
signals
-
udp / tcp / http
-
child_process: fork,send
-
cluster / compute-cluster
Signals
-
man signal (e.g. SIGHUP, SIGINT, SIGURG, etc...)
-
#include <signal.h>
-
Allow the manipulation of a process from outside its domain
-
Allow the process to manipulate itself or copies of itself (children)
-
addressed using PID (process id)
Signals
$ node server.js
server running with PID: 1905
Got a SIGTERM, exiting...
UDP: Internet User Datagram Protocol
-
man udp
-
#include <sys/socket.h>
-
simple, unreliable, connectionless
-
low overhead, fast
-
same `ip-addr:port` format as TCP/HTTP
UDP / Datagram Sockets
server.js
UDP / Datagram Sockets
client.js
UDP / Datagram Sockets
$ node server.js & node client.js
[2] 1148
listening on port 48945
server got msg: 'a datagram for you'
$ killall node
[1]- Exit 1 node server.js
TCP: Internet User Datagram Protocol
-
man tcp
-
builds non-blocking connection support upon sockets
-
reliable, flow-controlled, two-way transmission
of data
TCP Sockets
$ node server.js & node client.js
[1] 1764
server connected with client on port 8080
server sends a tcp message for you
$ killall node
[1]- Exit 1 node server.js
Child Process
-
Advanced means for asynchronously controlling subprocesses
-
Combines os.fork with tcp communication and pipes to simplify streaming message passing
-
Supports IPC through both signals (child.kill(signal) and bi-directional messages (child.send(message, [sendHandle]))
Child Process - Spawn
parent-spawn.js
Child Process - Spawn
$ node parent-spawn.js
child says (stdout): child was created with PID: 1084
child says (stderr): child is exiting with code: undefined and signal: undefined
Child Process - Fork
parent-fork.js
Child Process - Fork
$ node parent-fork.js
child was created with PID: 1089
child: got message from parent: hello from your parent
parent: got message from child: hi, thanks for the message!
Cluster
-
Easily create a network of processes that all share server ports
-
Made possible because `child_process` module rocks
Child Process - Fork
multi-core-server.js
It gets better: Lloyd's "compute-cluster"
-
"Fully load" Node if you have lots of cores
-
github.com/lloyd/compute-cluster
-
github.com/lloyd/fully_loaded_node
Demo! Lloyd's "Fully Loaded Node"
Demo! Lloyd's "Fully Loaded Node"
Thanks!
-
Node.js core devs and contributors for awesome docs
-
Lloyd Hilaiel - for being brilliant on performance
-
Alex Young with http://dailyjs.com for the solid unix series