1、net The module is basically API

To use Node.js Of net The module implements a command line chat room , You have to understand NET Modular API Use .NET modular API There are two main categories :Server and Socket class 、 Factory method .

Server The class is shown in the figure below :

net.Server Class can be used to create a TCP Or local server , Inherited EventEmitter.

Socket The categories are as follows :

net.Socket Class is usually used to create a socket Client or net.Server connection Parameters of the event .

The factory method is as follows :

The above three figures show API Use , Actually NET The internal principle of the module and C++ Network programming is similar , It's all the following steps .

Server side :

  1. establish socket Socket
  2. binding IP And port
  3. Start listening
  4. Wait for the client to connect
  5. Communicating with clients
  6. close socket

client :

  1. establish socket Socket
  2. Connect server The server
  3. Communicate with the server
  4. close socket

As shown in the figure below :

2、 Design and implementation of chat room

I learned from it NET modular API Use , Next, we will start to implement the command line chat room , What we don't have to do is complicated , Just implement the following functions :

  1. User defined nickname , Non modifiable
  2. When a new user enters the chat room , Or the user leaves the chat room , Broadcast to other users
  3. Users send messages , Need to broadcast to other users
  4. Establish heartbeat mechanism between client and server
  5. User input 'exit' perhaps 'quit' You can exit the chat room

After defining the function , I started to write the code . I will not analyze it step by step here , Go straight to the code , The first is the server :


const net = require('net');
const server = net.createServer();
const clients = {};// Save the client connection
var client = null;// Current customer connection
var uid = 0;
// Activate the heartbeat mechanism
var isOnline = !0;
var keepAliveTimer = socket.timer = setInterval(()=>{
client = socket;
isOnline = !1;
client = socket;
console.log(`client disconnected.\n\r`);
client = socket;
var msg = JSON.parse(chunk.toString());
isOnline = !0;
console.log(`listening on ${server.address().address}:${server.address().port}\n\r`);
server.listen(8060);// Start listening
* Handle user information
function dealMsg(msg){
const cmd = msg.cmd;
const funs = {
if(typeof funs[cmd] !== 'function') return !1;
* Release connection resources
function freeConn(conn){
delete clients[conn.uuid];
* The first time a user enters a chat room
function login(msg){
var uuid = '';
uuid = getRndStr(15)+(++uid);// Generating users ID
client.write(` Welcome ,${msg.nick}: There's a total of ${Object.keys(clients).length} A little friend is chatting .\r\n`)
client.nick = msg.nick;
client.uuid = uuid;
clients[uuid] = client;
broadcast(` System :${msg.nick} Into the chat room .`); }
* Broadcast news
function broadcast(msg){
if((clients[uuid]!=client)& clients[uuid].writable){
* Quit the chat room
function quit(nick){
var message = ` buddy ${nick} Quit the chat room .`;
} function chat(msg){
return ;
var message = `${msg.nick} say :${msg.msg}`;
* Randomly specify the length (len) String
function getRndStr(len=1){
var rndStr = '';
for (; rndStr.length < len; rndStr += Math.random().toString(36).substr(2));
return rndStr.substr(0, len);

The client code is as follows :


const net = require('net');
const cout = process.stdout;
const cin = process.stdin; var client = null;
var nick = ''; cout.write(` Please enter your nickname :`);
// Listen for command line input
if(client === null){
nick = (chunk+'').replace(/[\r\n]/ig,"");
msg = (chunk+'').replace(/[\r\n]/ig,"");
cmd: 'chat',
msg: msg,
nick: nick
// If the input is exit or quit Then disconnect and exit
if(msg.toLowerCase() == 'exit' || msg.toLowerCase() == 'quit'){
cout.write(` You say? :${msg}\n\r`);
cout.write(` Please enter your nickname :`);
}); function addListener(client) {
client.on('connect', () => {
cout.write(` Connected to server \n\r`);
cmd: 'login',
msg: 'hello server',
nick: nick
client.on('end', (chunk) => {
cout.write(` Disconnect from the server .\n\r`);
client.on('data', (chunk) => {
// If it's a heartbeat message, respond keep command
cmd: 'keep',
msg: '',
nick: nick
return ;
client.on('error', (err) => {
cout.write(`an error has occured.\n\r${err}`);
* establish socket And connect to the server
function createClient(){
console.log('\033[2J');// Clear screen operation
cout.write(` Input 'EXIT OR QUIT' Quit the chat room .\r\n`);
client = new net.Socket()

The results are as follows :

Here we are , A command line chat room is done .

utilize Node.js Of Net Module to achieve a command line multi chat room more related articles

  1. node.js Use in yargs To handle command line arguments

    yargs Library can handle command line parameters easily . One . install yargs npm install yargs --save Two . Read the command line arguments const yargs = require('yargs'); le ...

  2. Node.js actual combat 5: Operating system and command line .

    Nodejs There are some built-in ways to query operating system information : Such as : process.arch Getting the system is 32 A still 64 position , process.platform Get the type of the system . routine : console.log(p ...

  3. stay nginx Set up in the server node.js After the local server , utilize Node.js Of FS modular , Realize simple data writing and reading

    First in server.js Introduced inside : var fs = require('fs');   And then write  //  Go to writeme.txt file   Write something     fs.writeFile('./writem ...

  4. 【Node.js】 utilize node.js Build a server and visit static web pages

    node.js It's a server language , Here's how to use node.js Provided to us api To build the server , And visit static web pages The project structure is as follows ------------------------------------ ...

  5. elementary analysis Node.js Of vm Modules and running untrusted code

    In some systems , We want to give users the ability to insert custom logic , except  RPC  and  REST  outside , Running code provided by customers is also a common method , The advantage is that it can greatly reduce the time spent on the network .JavaScript It's a very popular and ...

  6. Node.js Of Formidable Use of modules

    Today I sum up Node.js Of Formidable Use of modules , Here's a brief explanation . 1)     establish Formidable.IncomingForm object var form = new formidab ...

  7. Node.js course 04 - Module system

    Preface : Node.js The modular system of is similar to C/C++ File reference for , You can declare objects , You can also define classes Create objects . People understand that , Just a simple . Definition : In order to make Node.js Files can be called to each other ,Node.js Provides a Jane ...

  8. Node.js Of cluster modular ——Web Back end multi process service

    as everyone knows ,Node.js It's single threaded , A single Node.js Processes don't make the most of multicore .Node.js from v0.6.0 Start , newly added cluster modular , Give Way Node.js Development Web The service , It's very convenient to make full use of multi-core computers ...

  9. Node.js introduction : Module mechanism

    CommonJS standard       As early as Netscape Soon after its birth ,JavaScript I've been exploring the way of local programming ,Rhino It's the representative product . But then the server JavaScript The way to go is to refer to many server-side languages ...

Random recommendation

  1. JavaScript essays 7

    BOM (1). window.open(' window ','_self perhaps _blank');// Open a new browser window example var win = window.open('about:blank');// obtain ...

  2. Start learning nodejs —— Debugging

    Learn a new technology , There's going to be a lot of holes , We need to find these pits , Find out why these pits appear and how they work . This operation is called debugging . There are many methods and tools for program debugging , Here I'd like to summarize what I'm learning nodejs In the process of , Learn and use ...

  3. Windows The structures, PHP Environmental Science :Apache+PHP+MySQL

    This article briefly records Windows The structures, PHP The process of the environment , Some details can be found in this article , This article will not repeat preparation : Windows Next, build it by hand PHP The environment needs to download the corresponding software first , It should be noted that Apache And PHP Of ...

  4. python Single asterisk before function parameter (*) And the double star (**) The difference between

    stay python You can often see one or two asterisks in front of the input parameter in the function of : for example def foo(param1, *param2): def bar(param1, **param2): These two usages are actually used to ...

  5. Linux Network programming 9&mdash;&mdash; Yes TCP And UDP Simple packaging 2.0

    Please refer to the last blog for the operation of generating and using the dynamic library . Here's just the code for the improved version . Code my_socket.h #ifndef __MY_SOCKET_H__ #define __MY_SOCKE ...

  6. arcgis Data files use

    dem Data open , preservation , Use open

  7. smail Syntax reference

    Dalvik opcodes Author: Gabor Paller Vx values in the table denote a Dalvik register. Depending on th ...

  8. Customize View-6 Status button slide Click on

    View public class SwitchButton extends View implements OnClickListener, OnTouchListener {     privat ...

  9. How to quickly become effective when joining a new company

    How to quickly become effective when joining a new company The other day my colleague Richard asked ...

  10. SimpleMembership

    lately 2 Months since , Always learning MVC, From the very beginning 2, All the way to the latest 4. From the original aspx To the present Razor engine , The more you study, the happier you are , The more you learn, the more addictive you become . Prepare for new projects recently , Intended use MVC4,VS2012+SQL2012, Anyway ...