So far in this chapter, we’ve explored the server side of Node.js sockets. Here we’ll write a client program in Node.js to receive JSON messages from our net-watcher-json-service program. We’ll start with a naive implementation, and then improve upon it through the rest of the chapter.
Open an editor and insert this:
| | 'use strict'; |
| | const net = require('net'); |
| | const client = net.connect({port: 60300}); |
| | client.on('data', data => { |
| | const message = JSON.parse(data); |
| | if (message.type === 'watching') { |
| | console.log(`Now watching: ${message.file}`); |
| | } else if (message.type === 'changed') { |
| | const date = new Date(message.timestamp); |
| | console.log(`File changed: ${date}`); |
| | } else { |
| | console.log(`Unrecognized message type: ${message.type}`); |
| | } |
| | }); |
Save this program as net-watcher-json-client.js.
This short program uses net.connect to create a client connection to localhost port 60300, then waits for data. The client object is a Socket, just like the incoming connection we saw on the server side.
Whenever a data event happens, our callback function takes the incoming buffer object, parses the JSON message, and then logs an appropriate message to the console.
To run the program, first make sure the net-watcher-json-service is running. Then, in another terminal, run the client:
| | $ node net-watcher-json-client.js |
| | Now watching: target.txt |
If you touch the target file, you’ll see output like this:
| | File changed: Mon Dec 21 2015 05:34:19 GMT-0500 (EST) |
Success! This program works, but it’s far from perfect. Consider what happens when the connection ends or if it fails to connect in the first place. This program listens for only data events, not end events or error events. We could listen for these events and take appropriate action when they happen.
But there’s actually a deeper problem lurking in our code—caused by assumptions we’ve made about message boundaries. In the next section we’ll develop a test that exposes this bug so we can fix it.