Node. js entry-2. Create a simple chat room

Source: Internet
Author: User

This article will introduce the net module of node. js by developing a simple chat room.

  

  I. The first version only sends information to the client

 

First, implement a simple version with the following code:

var net=require('net');var chatServer=net.createServer();chatServer.on('connection',function(client){    client.write('hi!\n');    client.write('bye!\n');    client.end();})chatServer.listen(9001);

  Code Description:  

1. Because we want to use TCP as the communication protocol, TCP-related classes in node are placed in the net module, so I need to reference net first.

2. a tcp server is created for us through net. createserver.

3. Use the on method to listen to Connection events. Every time a new client connects to our TCP server, it will trigger the corresponding connection method and output 'Hi! 'to the client! Bye! . Then close the connection through client. End.

4. The program finally listens to port 9001 through chatserver. Listen (9001.

 

  Running Server:

Use the webstorm debugging tool to run our server.

  

  Run the client:

Open the window command line tool,

Run the following command:

telnet 127.0.0.1 9001

Press enter to output the following results:

 

  Note:

I encountered a small problem when practicing the above example. I first used port 9000 and reported an error when running the program.

events.js:66        throw arguments[1]; // Unhandled 'error' event                       ^Error: listen EADDRINUSE    at errnoException (net.js:769:11)    at Server._listen2 (net.js:909:14)    at listen (net.js:936:10)    at Server.listen (net.js:985:5)    at Object.<anonymous> (D:\workspace\nodejs\chatroom\chatServer.js:8:12)    at Module._compile (module.js:449:26)    at Object.Module._extensions..js (module.js:467:10)    at Module.load (module.js:356:32)    at Function.Module._load (module.js:312:12)    at Module.runMain (module.js:492:10)

The 'addrinuse' is confusing and does not know what it means. 'Addrinuse' should be the abbreviation of 'error address in use. Later, I found a reasonable explanation using Google, saying that the port you listened to has been used. I changed the port to 9001, and everything is normal.

When an exception occurs, I don't know if node has any help. The exception information provided by node alone cannot solve the problem. Maybe the best helper is Google.

 

  2. The second edition can receive client information:

The Code is as follows:

var net=require('net');var chatServer=net.createServer();var clientList=[];chatServer.on('connection',function(client){    client.write('hi!\n');    clientList.push(client);    client.on('data',function(data){        for(var i= 0,len=clientList.length;i<len;i++){            if(client!=clientList[i]){                clientList[i].write(data);            }        }        console.log(data);    });})chatServer.listen(9001);

This version has two changes than the first version. One is to add the on method of the client, and the other is to remove the client. End (); method. The on method of the client adds data events, so that each time the client sends data, the server can receive the data. The reason for removing client. End () is that if the link is closed and the client sends new data, the server cannot receive the data.

Let's take a look at the running results. 'hello' indicates the client input information, and the red line indicates the information received by the server. Note that it is binary data, we need to do the corresponding processing to convert it into a string, and we will introduce it later in the course.

 

  3. The third edition enables communication between the client and the server:

Here we need to cache each client in an array variable, traverse the array, and use the client. Write () method to respond to each client. Let's look at the Code:

var net=require('net');var chatServer=net.createServer();var clientList=[];chatServer.on('connection',function(client){    client.write('hi!\n');    clientList.push(client);    client.on('data',function(data){        for(var i= 0,len=clientList.length;i<len;i++){            if(client!=clientList[i]){                clientList[i].write(data);            }        }        console.log(data);    });})chatServer.listen(9001);

We have created a clientlist to store client connections. Every time a new connection comes in, the client object is saved in an array. Next, determine whether the retrieved client is the current client. If not, output data.

  

  Note:

Note the 'len = clientlist. length' section. We store clientlist. length in the variable Len to improve program performance. In the I <Len operation, you do not need to obtain clientlist. Length every time. You can use this method in your own program, especially when the array is large.

  

Let's take a look at the running result. To open multiple Telnet links, red indicates the input information, and blue indicates the output information:

  Iv. Final Version

We have added an end event for the customer to disconnect the link. The client does not exist during the end event and message sending process.

var net=require('net');var chatServer=net.createServer();var clientList=[];chatServer.on('connection',function(client){    client.name=client.remoteAddress+':'+client.remotePort;    broadcast('hi,'+ client.name +' join!\r\n',client);    client.write('hi,'+ client.name +'!\r\n');    clientList.push(client);    client.on('data',function(data){        broadcast(client.name+' say:'+ data+'\r\n',client);    });    client.on('end',function(){        broadcast('hi,'+ client.name +' quit!\r\n',client);        clientList.splice(clientList.indexOf(client),1);    });})function broadcast(message, client) {    var cleanup=[];    for(var i= 0,len=clientList.length;i<len;i++){        if(client!==clientList[i]){            if(clientList[i].writable){                clientList[i].write(message);            }else{                cleanup.push(clientList[i]);                clientList[i].destroy();            }        }    }    for(var i= 0,len=cleanup.length;i<len;i++){        clientList.splice(clientList.indexOf(cleanup[i]),1);    }}chatServer.listen(9001);

Running effect:

Three customers are linked to the server, and one of them says 'Hello' to the other two '.

One customer closes the link:

 

Today's example ends.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.