Node. js BASICS (10) use the net module and Readline module to implement Socket communication, and node. jsreadline

Source: Internet
Author: User

Node. js BASICS (10) use the net module and Readline module to implement Socket communication, and node. jsreadline

The socket communication of Node. js is very similar to that of C ++ and Java. Those who have learned the socket communication of these two languages can quickly master the socket communication of Node. js. Next we will learn about socket communication of Node. js for the purpose of implementing the server and client of an Echo server.

The Echo server refers to a server where the client sends a message to the server, and the server returns the message intact to the client.

Server

The implementation of the server is divided into three steps:
-Create a server using createServer
-Listen to the specified port using the listen method of the server and wait for the client to access
-Use a socket object to listen for data, close, and other events for interaction with the client.

The following is the server code:

/*** Created by Administrator on 2015/9/8. */var net = require ('net'); // The server uses ar host = '2017. 0.0.1 '; // PORT number var PORT = 7001; // create a TCP server instance and call the listen function to start listening to the specified PORT. // input the net. the callback function of createServer () is used as the processing function of the "connection" event // in each "connection" event, the socket Object received by the callback function is unique. net. createServer (function (sock) {// gets a socket connection and outputs the client to the console. log ('ccted: '+ sock. remoteAddress + ':' + sock. remotePort); // Add a "data" event handler sock for this socket instance. on ('data', function (data) {console. log ('data' + sock. remoteAddress + ':' + data); // when this data is sent back, the client will receive data from the server and implement ECHO server sock. write (''+ data) ;}); // Add a" close "event handler sock for this socket instance. on ('close', function (data) {console. log ('closed: '+ sock. remoteAddress + ''+ sock. remotePort );});}). listen (PORT, HOST); console. log ('server listening on '+ HOST +': '+ PORT );

When createListener is used, a callback function is passed in and called when the client connects to the server. The data and close events are listened to in the callback function.

  • Data event: this event is triggered when a message is sent from the client.
  • Close event: this event is triggered when the client is disconnected.
Client

Because we want to implement the Echo server, we naturally need to implement Input and Output. Here, I used the Readline module introduced in the previous article to implement the input and output of the console, if you are not familiar with this module, You can first take a look at the introduction of the Readline module.

Similar to the server, the client can be implemented in three steps:
-Create a socket
-Connection to the server with the specified IP address and port number
-Monitors data, close, and other events to complete interaction with the server.

The client code is as follows:

/*** Created by Administrator on 2015/9/8. */var net = require ('net'); var readline = require ('readline'); // create the readline interface rl = Readline. createInterface (process. stdin, process. stdout); var HOST = '2017. 0.0.1 '; var PORT = 7001; var client = new net. socket (); client. connect (PORT, HOST, function () {console. log ('ted cted to: '+ HOST +': '+ PORT); // after the connection is established, run the command line TO input rl. setPrompt ('test> '); rl. prompt ();});/ /Add the "data" event handler function to the client. // data is the data client sent back by the server. on ('data', function (data) {// output the message console from the server. log ("" + data); rl. prompt () ;}); // Add the "close" event handler client to the client. on ('close', function () {console. log ('Connection closed '); process. exit (0) ;}); rl. on ('line', function (line) {switch (line. trim () {case 'close': rl. close (); return;} client. write (line. trim (); rl. prompt ();}). on ('close', function () {console. log ('G Ood bye! '); Client. end ();});

It should be noted that the client socket listens to data and close events, and our input and output modules also listen to their own line and close events. The former is the client variable, and the latter is the rl variable, make a difference.

When close is input, the following process occurs:
1. Calling Readline. close () in the line event triggers the close event of Readline;
2. In the close event of Readline, call client. end () to end the client, thus triggering the close event of the client;
3. Execute process. exit (0) in the close event listener of the client ).

Communication result

Client:

Server:

Communication involves three processes:
1. After receiving user input, the client sends the information to the server;
2. After receiving information from the client, the server returns the original message to the client;
3. The client receives the server information and displays it.

Here is a brief introduction to the basic usage of Node. js. For more information, see the official API documentation.

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.