Building a Simple Networked Application in Node.js using the `net` Module

Learn the fundamentals of network programming in Node.js using the `net` module. This tutorial provides a practical example of building a basic TCP client-server application, demonstrating how to handle socket connections, send and receive data, and manage network communication.



Building a Simple Networked Application with Node.js's `net` Module

Introduction

Node.js's `net` module provides tools for building network applications using TCP sockets. Sockets enable two-way communication between applications over a network. This tutorial demonstrates a basic client-server example using the `net` module.

Creating a TCP Server

This example creates a simple TCP server that listens for connections on a specified port and sends a message to each connected client:

TCP Server Code (net_server.js)

const net = require('net');

const server = net.createServer((socket) => {
  socket.end('goodbye\n');
}).on('error', (err) => {
  throw err; 
});

server.listen(() => {
  const address = server.address();
  console.log('opened server on %j', address);
});

Run this using `node net_server.js` from your terminal. Note that this code chooses a random available port for the server to listen on.

Creating a TCP Client

This client connects to the server on the same port, sends a message, receives a response, and then disconnects:

TCP Client Code (net_client.js)

const net = require('net');

const client = net.connect({ port: 50302 }, () => { //Replace 50302 with the actual port from the server
  console.log('connected to server!');
  client.write('world!\r\n');
});

client.on('data', (data) => {
  console.log(data.toString());
  client.end();
});

client.on('end', () => {
  console.log('disconnected from server');
});

Run this using `node net_client.js` from a separate terminal. Make sure the port number matches the port your server is listening on.

Important Note: Port Matching

The server and client must use the same port number for a successful connection. The server in this example picks a random available port; you need to find out what port was selected by the server and use that same port in the client's `net.connect()` method. The output from the server after it starts will tell you which port was assigned.

Conclusion

This tutorial demonstrated basic TCP socket communication using Node.js's `net` module. It's a starting point for building more complex networked applications. Always include robust error handling in your code to make your application more resilient to network issues.