About Bevry

Bevry's Learning Centre

  doing everything we can to empower developers

Basic Server

var http = require('http')
var count = 0
http.createServer(function (req, res) {
    console.log('Received', ++count, 'requests so far')
    res.writeHead(200, {'Content-Type': 'text/plain'})
    res.end('hello world\n')
}).listen(8000)

Test it: curl http://localhost:8000

Server with Pause

var http = require('http')
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'})
    res.write('hello\n')
    setTimeout(function () {
        res.end('world\n')
    }, 2*1000)
}).listen(8000)

Bench it: ab -n 100 -c 100 http://localhost:8000/

Echo Server

var net = require('net')
net.createServer(function (socket) {
    socket.write('Talk to me.\n')
    socket.on('data', function (data) {
        socket.write(data.toString().toUpperCase())
    })
}).listen(8000)

Talk with it: nc localhost 8000

Chat Server

// Application
var net = require('net')
var sockets = []
net.createServer(function (socket) {
    sockets.push(socket)
    socket.write('Talk to me.\n')

    socket.on('data', function (data) {
        for ( var i = 0; i < sockets.length; ++i ) {
            sockets[i].write(data)
        }
    })

    socket.on('end', function () {
        var index = sockets.indexOf(socket)
        sockets = sockets.slice(0, index).concat(sockets.slice(index + 1))
    })
}).listen(8000)

Talk with it: nc localhost 8000

Supplemental

Echo Server with Transform Stream

'use strict'

class UC extends require('stream').Transform {
    _transform (data, encoding, next) {
        next(null, data.toString().toUpperCase())
    }
}

class Reverse extends require('stream').Transform {
    _transform (data, encoding, next) {
        next(null, data.toString().split('').reverse().join(''))
    }
}

require('net').createServer(function (socket) {
    socket.write('Talk to me.\n')
    socket.pipe(new UC()).pipe(new Reverse()).pipe(socket)
}).listen(8000)

Talk with it: nc localhost 8000

Chat Server with Extras

// Application
var net = require('net')
var count = 0
var sockets = {}
function broadcast (message) {
    for ( var key in sockets ) {
        if ( sockets.hasOwnProperty(key) ) {
            sockets[key].write(message)
        }
    }
}
net.createServer(function (socket) {
    sockets[socket.index = count++] = socket
    socket.write('Hello user ' + socket.index + '\n')
    broadcast('User ' + socket.index + ' joined\n')

    socket.on('data', function (data) {
        broadcast('User ' + socket.index + ' says: ' + data.toString())
    })

    socket.on('end', function () {
        delete sockets[socket.index]
        broadcast('User ' + socket.index + ' left\n')
    })
}).listen(8000)

Talk with it: nc localhost 8000