Node.js Tutorial
- Node.js Tutorial
- Install Node.js on Windows
- Install Node.js on Linux/Ubuntu/CentOS
- Node.js First Example
- Node.js Console
- Node.js REPL
- Node.js Package Manager
- Node.js Command Line Options
- Node.js Global Objects
- Node.js OS
- Node.js Timer
- Node.js Errors
- Node.js DNS
- Node.js Net
- Node.js Crypto
- Node.js TLS/SSL
- Node.js Debugger
- Node.js Process
- Node.js Child Process
- Node.js Buffers
- Node.js Streams
- Node.js File System (FS)
- Node.js Path
- Node.js StringDecoder
- Node.js Query String
- Node.js ZLIB
- Node.js Assertion Testing
- Node.js V8
- Node.js Callbacks
- Node.js Events
- Node.js Punycode
- Node.js TTY
- Node.js Web Module
- NestJS
Node.js MySQL
Node.js MongoDB
Nodejs Difference
Node.js MCQ
Node.js Express
Nodejs Interview Questions
Node.js Net
Node.js provides the ability to perform socket programming. We can create chat application or communicate client and server applications using socket programming in Node.js. The Node.js net module contains functions for creating both servers and clients.
Node.js Net Example
In this example, we are using two command prompts:
- Node.js command prompt for server.
- Window's default command prompt for client.
server:
File: net_server.js
- const net = require('net');
- var server = net.createServer((socket) => {
- socket.end('goodbye\n');
- }).on('error', (err) => {
- // handle errors here
- throw err;
- });
- // grab a random port.
- server.listen(() => {
- address = server.address();
- console.log('opened server on %j', address);
- });
Open Node.js command prompt and run the following code:
- node net_server.js
client:
File: net_client.js
- const net = require('net');
- const client = net.connect({port: 50302}, () => {//use same port of 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');
- });
Open Node.js command prompt and run the following code:
- node net_client.js