Communicating over sockets
One way to look at a socket is as a special file. Like a file, it's a readable and data container. On some operating systems, network sockets are literally a special type of file whereas, on others, the implementation is more abstract.
At any rate, the concept of a socket has changed our lives because it allows machines to communicate and to coordinate I/O across a network. Sockets are the backbone of distributed computing.
In this recipe, we'll build a TCP client and server.
Getting ready
Let's create two files, client.js
and server.js
, and open them in our favorite editor.
How to do it...
First, we'll create our server.
In server.js
, let's write the following:
const net = require('net') net.createServer((socket) => { console.log('-> client connected') socket.on('data', name => { socket.write(`Hi ${name}!`) }) socket.on('close', () => { console.log('-> client disconnected') }) }).listen(1337, 'localhost')
Now for the client...