Transmission Control Protocol (TCP)

It is a connection-oriented communication protocol that helps the exchange of message between the commuting device

The most common protocol in networks that use the Internet Protocol(IP); together they are sometimes referred to as TCP/IP.

TCP takes messages from an application/server and divides them into packets, which can then be forwarded by the devices in the network — switches, routers, security gateways to the destination.

It ensures a connection is established and maintained until the exchange between the application/servers sending and receiving the message is complete.

Internet Protocol (IP)

Internet Protocol has some set of rules for how data should be transferred over the public network.

Often works in conjunction with TCP, which divides the traffic into packets for efficient transport through the Internet; together they are referred to as TCP/IP.

TCP socket programming in Node.js

Eager to know how sockets are programmed in Node? There are three variants of sockets in Node:

In this particular post, I will show you the basics of TCP socket programming in Node.js.

There are two categories of TCP socket programs you can write:

Programming TCP sockets in Node requires the net module, which is an asynchronous wrapper for network programming. The net module is capable of many things, but for today we'll just focus on creating a TCP server and a client.

Writing TCP Server

var net = require("net");var HOST = "127.0.0.1";var PORT = 6969;
net
.createServer(function (sock) {
console.log("CONNECTED: " + sock.remoteAddress + ":" + sock.remotePort); sock.on("data", function (data) { console.log("DATA " + sock.remoteAddress + ": " + data); sock.write('You said "' + data + '"');
});
sock.on("close", function (data) { console.log("CLOSED: " + sock.remoteAddress + " " + sock.remotePort); });}).listen(PORT, HOST);console.log("Server listening on " + HOST + ":" + PORT);

Writing TCP Client

var net = require("net");var HOST = "127.0.0.1";var PORT = 6969;var client = new net.Socket();client.connect(PORT, HOST, function () {      console.log("CONNECTED TO: " + HOST + ":" + PORT);      client.write("I am Chuck Norris!");});
client.on("data", function (data) { console.log("DATA: " + data); client.destroy();});
client.on("close", function () { console.log("Connection closed");});

So that’s the very basics of TCP socket programming in Node.js, hope it helped you understand socket programming in Node better.