NET module provides an asynchronous network wrapper for TCP network programming, which contains methods for creating servers and clients
Create a TCP server
net.createServerMethod
Creating a client to connect to a server
net.connectMethod
Simple chat room service side
Chatserver.js
varNET = require (' net ');//Create a TCP servervarServer =net.createserver ();//Store all client socketsvarsockets = [];//receiving Client connection requestsServer.on (' Connection ',function(socket) {Console.log (' Got A new connection '); Sockets.push (socket); //get the data that the client sent overSocket.on (' Data ',function(data) {Console.log (' Got data: ', data); //The server broadcasts data and forwards the data from the client to all other clientsSockets.foreach (function(othersocket) {if(Othersoecket!==socket) {othersocket.write (data); } }); ]); //Remove the client that closed the connection from the Server broadcast listSocket.on (' Close ',function() {Console.log (' A Client Connection closed '); varindex =sockets.indexof (socket); Sockets.splice (Index,1); });}); Server.on (' Error ',function(Err) {Console.log (' Server error: ', err.message);});//Listening for client disconnect eventsServer.on (' Close ',function() {Console.log (' Server closed ');});//Start the serviceServer.listen (8080);
Simple Chat Room Client
varNET = require (' net ');p rocess.stdin.resume ();p rocess.stdin.setEncoding (' UTF8 ');//connecting to a servervarClient = Net.connect ({port:8080},function() {Console.log (' Connected to server '); //gets the input stringConsole.log (' Input: '); Process.stdin.on (' Data ',function(data) {//send the input string to the serverConsole.log (' Input: '); Client.write (data); //close connection when entering ' close ' string if(data = = ' close\n ')) {client.end (); } });});//get the data sent over the serverClient.on (' Data ',function(data) {Console.log (' Other user\ ' input ', data.tostring ());});//Disconnect ConnectionClient.on (' End ',function() {Console.log (' Disconnected from server '); //exiting the client programprocess.exit ();});
Process is a node. JS Global Module
process.stdinUsed to get a readable stream from a standard input
Execute node chatserver.js start server
Execute the node Chatclient.js startup client to start multiple
Input to this client on the server and other clients
node. JS's net Module