1702145823

Creating TCP server and client communication


Sockets allow machines and devices to communicate. Sockets are also used to coordinate I/O across networks. The term socket is used to refer to one endpoint of a two-way network communication link. Sockets enable us to build real-time web applications, such as instant messaging applications. In this recipe, we will create a TCP server and a TCP client and allow them to communicate. TCP stands for Transmission Control Protocol. TCP provides a standard that allows devices to communicate over a network. ## Getting ready $ mkdir communicating-with-sockets $ cd communicating-with-sockets $ touch server.js $ touch client.js ```javascript const net = require("net"); const HOSTNAME = "localhost"; const PORT = 3000; net .createServer((socket) => { console.log("Client connected.") }) listen("PORT, connected."); socket.on("data", (name) => { socket.write("Hello "+name+"!"); }) ``` Now lets create the client. Again, we need to start by importing the net module in client.js: ```javascript const net = require("net"); const HOSTNAME = "localhost"; const PORT = 3000; const socket = net.connect(PORT, HOSTNAME); socket.write("world"); ``` We also need to add a function that will listen for data returned by the socket: ```javascript socket.on("data", (data) => { console.log(data.toString()) }); ``` Run your server with the following command: $ node server.js. In a second shell, run client.js: $ node client.js In the shell where you e running server.js, you should see the output, Client connected: $ node server.js Client connected.

(0) Comments

Welcome to Chat-to.dev, a space for both novice and experienced programmers to chat about programming and share code in their posts.

About | Privacy | Terms | Donate
[2024 © Chat-to.dev]