Monday, July 29, 2019

What is 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
  1. const net = require('net');  
  2. var server = net.createServer((socket) => {  
  3.   socket.end('goodbye\n');  
  4. }).on('error', (err) => {  
  5.   // handle errors here  
  6.   throw err;  
  7. });  
  8. // grab a random port.  
  9. server.listen(() => {  
  10.   address = server.address();  
  11.   console.log('opened server on %j', address);  
  12. });  
Open Node.js command prompt and run the following code:
  1. node net_server.js  
Node.js net example 1
client:
File: net_client.js
  1. const net = require('net');  
  2. const client = net.connect({port: 50302}, () => {//use same port of server  
  3.   console.log('connected to server!');  
  4.   client.write('world!\r\n');  
  5. });  
  6. client.on('data', (data) => {  
  7.   console.log(data.toString());  
  8.   client.end();  
  9. });  
  10. client.on('end', () => {  
  11.   console.log('disconnected from server');  
  12. });  
Open Node.js command prompt and run the following code:
  1. node net_client.js  
Node.js net example 2

Note: You must match the port. The client and server should have similar port for successful connection.

No comments:

Post a Comment