Well the Node.js will provides the ability to perform the socket programming. And we can create chat application or communicate client and server application by use of the socket programming in Node.js. And when we say about the Net module in Node.js, this will contains functions for both clients and servers creation.
Node.js Net Example
Here in this example we us two command prompt:-
(1)Node.js command prompt for server
(2)Windows's default command prompt for client.
server:
File: netserver.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);
});
Now open Node.js command prompt to run the below coe to execute .js file
node net_server.js
Now we will jump to client code
client:
File: netclient.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');
});
Now open Node.js command prompt to run the below coe to execute .js file
node netclient.js
serverclientNodeJS