Creating Socket Client Connections

So far in this chapter, we’ve explored the server side of Node sockets. Here we’ll write a client program in Node 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:

networking/net-watcher-json-client.js
​ 
​"use strict"​;
​ 
​const​
​ 
net = require(​'net'​),
​ 
client = net.connect({port: 5432});
​ 
client.on(​'data'​, ​function​(data) {
​ 
​let​ message = JSON.parse(data);
​ 
​if​ (message.type === ​'watching'​) {
​ 
console.log(​"Now watching: "​ + message.file);
​ 
} ​else​ ​if​ (message.type === ...

Get Node.js the Right Way now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.