We will first be building a banking server and a teller client. The banking server represents the bank vault, and the client is what tellers use to deposit and withdraw funds from the vault. But we're already getting ahead of ourselves. Let's start with the general bank scaffold.
To keep everything simple we will be building a simple TCP server that
understands JSON objects, using the core net
module and duplex-json-stream
:
// bank.js
var jsonStream = require('duplex-json-stream')
var net = require('net')
var server = net.createServer(function (socket) {
socket = jsonStream(socket)
socket.on('data', function (msg) {
console.log('Bank received:', msg)
// socket.write can be used to send a reply
})
})
server.listen(3876)
To interact with our bank, we will need a client that talks the same protocol. The server and client are asymmetric, just like in HTTP, so our clients will be ephemeral, while our server is where state lives.
// teller.js
var jsonStream = require('duplex-json-stream')
var net = require('net')
var client = jsonStream(net.connect(3876))
client.on('data', function (msg) {
console.log('Teller received:', msg)
})
// client.end can be used to send a request and close the socket
First extend the client to send {cmd: 'balance'}
to the bank, and have the
bank reply with {cmd: 'balance', balance: 0}
To test your application, open two terminals and run node bank.js
in one
session and run node teller.js
in the other. The teller should print out
Teller received: {cmd: 'balance', balance: 0}
and exit, while the bank should
print Bank received: {cmd: 'balance'}
and keep running.