Working with Node.js Net Module

Easy
33
7
18.3% Acceptance

In this lab, you will be working with the net module of Node.js, which provides an asynchronous network API for creating network applications. You will create a simple TCP server, listen to a particular port, and handle incoming connections and data.

Steps

  1. Import the net module:

The first step to using Node.js's net module is to import it using require. This makes the net object available to your code.

import net from 'net';
  1. Create the server:

Once you have imported the module, you can use net.createServer() to create a new TCP server. This method takes a callback function which will be called whenever a client connects to the server. This callback function itself takes a socket object as an argument; this socket object represents the connection to the client.

const server = net.createServer((socket) => { // code to be executed upon a new connection });
  1. Handle incoming connections:

Within the callback function passed to createServer(), you can set events for the socket object for various moments in the lifecycle of a connection. Here we can use console.log to print a message to the console whenever a new client connects.

const server = net.createServer((socket) => { console.log('Client connected'); });
  1. Send data to client:

We can use the socket.write() method to send a welcome message to a newly-connected client.

const server = net.createServer((socket) => { socket.write('Hello Net!'); });
  1. Handle client disconnection:

We can listen for the end event on the socket object to determine when a client has closed their connection. As with the connection event, we'll log this to the console.

const server = net.createServer((socket) => { socket.on('end', () => { console.log('Client disconnected'); }); });
  1. Start the server:

To start the server, you simply call server.listen() with the port number you want the server to listen on. Again, we'll log to the console to let us know that the server has started successfully.

server.listen(1337, () => { console.log('Server listening on 1337'); });

Make sure the export the server so that it can be used for testing

That's it! You've created a simple TCP server in Node.js using the net module. This server listens on port 1337, logs when clients connect and disconnect, and sends a message to clients when they connect.

Test your connection

Now you choose to manually test if your TCP connection is working correctly by created a new script.js which would contain the client code for interaction with the TCP connection.

Here is the code snippet for you

import net from 'net'; const client = net.connect({port: 1337}, () => { console.log('Connected to server!'); }); client.on('data', (data) => { // Will log the data received from the TCP server console.log(data.toString()); client.end(); }); client.on('end', () => { console.log('Disconnected from server'); });

You can run this file in a new terminal by typing the command yarn run nodemon script.js or simply node script.js if you don't want hot reloading enabled.