Purpose: To implement a chat room with the console
Using modules: net,process
The beginning of the nonsense: for beginners, it is important to understand the official documents first.
There are a lot of written chat rooms, mostly quoted third-party modules, will inevitably increase the novice learning burden, here I only use the official net and process modules.
Hope to give novice, better understand these two modules (NET module, process module supplemented)
Body:
The project mainly consists of two documents
Server.js: Server
Client.js: Client (can open multiple)
/*server.js*/
varNet=require (' Net ');varServer=net.createserver (), Clientlist=[];
Clientlist to save all clients connectedvaroptions={"host": "127.0.0.1", "Port": "1117"};
/* Add a method to the array to determine if obj exists in this array */array.prototype.contains=function(obj) { for(vari = 0; I < This. length; i++) { if( This[i]===obj) { return true; } } return false;} Server.on (' Connection ',function(client) {Client.name=client.remoteaddress+ ': ' +Client.remoteport; Console.log (Client.name+ ' already connected '); if(!clientlist.contains (client)) {Clientlist.push (client); } client.on (' Data ',function(data) {Console.log (Client.name+ ' +data); //send this client's information to all clients except this client for(vari = 0; i < clientlist.length; i++) { if(client!==Clientlist[i]) {Clientlist[i].write (Clientlist[i].name+ ' +data); } } }); Client.on (' Error ',function() {Console.log ( This. name+ ' An exception occurred '); }); Client.on (' End ',function() {Console.log ( This. name+ ' Disconnected ');
This client needs to be removed from the lientlist}); });
/*client.js*/
varNet=require (' Net ');varoptions={"host": "127.0.0.1", "Port": 1117};varClient=net.connect (Options,function() {Console.log ("Client is connected"); Consoleread (client);}); Client.on (' Data ',function(data) {Console.log (data.tostring ());});
/* The input is not supported by default because Nodejs console is running.
You need to use Process.stdin.resume (). Let it receive input information
Process.stdin.on (' data ', Function) to get the input content
If you do not need to re-enter, you need to use Process.stdin.pause () to stop accepting input information.
Parameter client: Current clients
*/functionconsoleread (client) {process.stdin.resume (); Console.log ("Enter Chat content:"); Process.stdin.setEncoding (' UTF8 '); Process.stdin.on (' Data ',function(chunk) {//process.stdin.pause (); if(Chunk.trim () = = = "End") {Console.log (' Disconnected and server connection '); Client.end (); }Else{client.write (chunk); } });
}
Here's a look at:
"Z13 District" Nodejs the original ecological module, write a chat room