Using the N|Solid Console with Express, Socket.io and the cluster module
This guide explains how to use the N|Solid Console with applications made with express
, socket.io
and the cluster
modules.
Installation
Please refer to our Quick Start Guide for instructions on how to install the latest version of N|Solid.
This example application uses the socket.io-redis
module that requires a redis server running, you can run it locally:
Now you can run your own application.
The application is a simple Express + Socket.io application, using the cluster
module and running multiple workers. The source code is:
File index.js
const
http = require
('http'
)
const
cluster = require
('cluster'
)
const
path = require
('path'
)
const
express = require
('express'
)
const
sio = require
('socket.io'
)
const
RedisStore = require
('socket.io-redis'
)
const
port = process.env.PORT || 3000
const
numCPUs = require
('os'
).cpus().length
if
(cluster.isMaster) {
var
workers = []
var
spawn = function
(i
) {
workers[i] = cluster.fork()
workers[i].on('exit'
, function
(worker, code, signal
) {
console
.log('respawning worker'
, i)
spawn(i)
})
}
cluster.on('fork'
, function
(worker
) {
return
console
.log('forked worker '
+ worker.process.pid)
})
cluster.on('listening'
, function
(worker, address
) {
return
console
.log('worker '
+ worker.process.pid + ' is now connected to '
+ address.address + ':'
+ address.port)
})
cluster.on('exit'
, function
(worker, code, signal
) {
return
console
.log('worker '
+ worker.process.pid + ' died'
)
})
for
(var
i = 0
; i < numCPUs; i++) {
spawn(i)
}
} else
{
const
app = express()
const
server = http.createServer(app)
const
io = sio.listen(server)
io.adapter(RedisStore({ host: 'localhost'
, port: 6379
}))
app.get('/'
, function
(req, res
) {
return
res.sendfile(path.join(__dirname, '/index.html'
))
})
io.sockets.on('connection'
, function
(socket
) {
console
.log('socket call handled by worker with pid '
+ process.pid)
return
socket.emit('news'
, {
hello: 'world'
})
})
server.listen(port)
}
File index.html
<
html
>
<
script
src
="/socket.io/socket.io.js"
></
script
>
<
script
>
var
socket = io();
socket.on('news'
, function
(data
) {
console
.log(data);
socket.emit('my other event'
, { my: 'data'
});
});
</
script
>
</
html
>
You can run it using this command:
$ NSOLID_COMMAND=9001
NSOLID_APPNAME=socket
.io-cluster nsolid index
.js
You should now see the N|Solid console overview with all the general data of the application.
The cluster view displays a dot in the graph for each worker. Clicking on a dot will provide more detailed information about that worker.