NodeJs concise tutorial

Posted by cicibo on Wed, 24 Jul 2019 06:09:41 +0200

NodeJs concise tutorial will start from scratch to learn about NodeJs and help JS developers build a full stack development technology stack!

Focus on getting more NodeJs articles

This article is the ninth chapter of NodeJs concise tutorial. It will introduce the basic operation of NodeJs net module (TCP server/client).

What is TCP?

Transmission Control Protocol (TCP) is a connection-oriented, reliable, byte-stream-based transport layer communication protocol defined by IETF RFC 793.

NodeJs uses net module to implement TCP server/client related functions.

Echo Server Development

Echo server is a server-side program that shows what the client sends. The main purpose is to debug whether the network and protocol work properly.

net.createServerTo create a server, the prototype of this method is as follows:

net.createServer([options][, connectionlistener]): net.Server

  • options <Object>

    • Allow Half Open < Boolean > indicates whether half-open TCP connections are allowed. Default value: false.
    • PauseOnConnect < Boolean > indicates whether the socket should be paused on the incoming connection. Default value: false.
  • ConnectionListener < Function > Client Connect Event Listener. Callback parameter is Socket (which can be considered as a client connection)

The return value is net.Server. The main methods of net.Server are as follows:

server.listen([port[, host[, backlog]]][, callback])

  • Port < number > listening port
  • Host < string > listening host
  • Backlog < number > Maximum length of queue to be connected
  • Callback < Function > Listen for Successful Callback Functions

server.js

const net = require('net');

const server = net.createServer(function (client) { // Create a server
    console.log(client.address().address, 'Successful connection'); // Print Client Address when Client Connection Successful

    client.on('error', function (e) {
        console.log(client.address().address, ' error >> ', e.message); // Connection error (such as abnormal disconnection of client)
    });

    client.on('data', function (data) { // Receive client data
        console.log(client.address().address, ' >> ', data.toString());
        client.write(data); // Write data to client
    });

    client.on('end', function () { // Normal disconnection of client
        console.log(client.address().address, 'Disconnect');
    });
});

server.on('error', function (e) { // Server errors (such as failed startup, port occupancy)
    console.log('Server Startup Failure', e);
});

server.listen(10000, function () {
    console.log('Start successfully, address', server.address().address);
});
  1. Execution of node server.js shows that the output started successfully, address xxx
  2. Open the terminal and execute telnet localhost 10000. You can see the output as follows (if different, please discuss in groups):

    Trying ::1...
    Connected to localhost.
    Escape character is '^]'.
  3. The terminal continues to input the following characters:

    helloworld
  4. The server will reply

    hello world

The Echo server has been tested for development. Although the amount of code is not much, it demonstrates the process of developing a TCP server from scratch, which is much more convenient than developing a TCP server in C language.

TCP Client

net.connectTargets can be connected TCP The prototype of the method is as follows:

net.connect(port[,host][,connectionListener])

  • Port < number > connection port
  • Host < string > connect to host
  • ConnectionListener < Function > Callback for successful connection

Or take the server that just listened to 10,000 ports as an example to develop the client

client.js

const net = require('net');

const client = net.connect(10000, 'localhost', function () { // Connecting servers
    console.log('Successful connection to server');

    client.write('I am a client'); // Send data to server

    client.on('data', function (data) { // Receive server-side data
        console.log('Server-side message', data.toString());
        client.end(); // Disconnect
    });

    client.on('end', function () { // Connection disconnection event
        console.log('Disconnection of server');
    });
});

Ensure that the server is open, execute the js, the output is as follows:

Successful connection to server
 Server Message I am Client
 Disconnection of server

epilogue

NodeJs TCP server and client development is over, but the learning of TCP protocol goes far beyond this, including custom protocol development, TCP packet sticking and so on. This piece of problematic can be scanned code plus group communication:

Topics: node.js socket network C