node. JS Network Programming

Source: Internet
Author: User

node. JS provides a platform for the JavaScript language to run on the server, with its event-driven, non-blocking I/O mechanism making it ideal for developing I/O-intensive applications running on distributed devices. Distributed applications require node. js to be friendly to network communications, in fact, node. JS also provides a very powerful network communication function, this article mainly discusses how to use node. js for network programming.

First, the concept of network programming is "the use of sockets to achieve inter-process communication purposes." Typically, we want to use the features that the network provides, which can be in the following ways:

1. Use the network communication function provided by the application software to obtain the network service, the most famous is the browser, it uses the HTTP protocol on the application layer, the transport layer is based on the TCP protocol;

2. Use shell commands in command line mode to obtain the network services provided by the system, such as TELNET,FTP, etc.

3. Use the programmatic way to get the network service that the operating system provides to us through the system call.

The main purpose of this paper is to explore how to get the network service provided by the operating system in node. js to achieve the different host interprocess communication. Now looking back at the concept of network programming, here comes the concept of a socket, the so-called socket, actually two different processes to communicate between the port (where the port differs from the usual port in the IP address), it is a network hierarchy model in the network layer and the following layers of the operation of a package , in order to enable developers to invoke the Web services provided by the operating system in various languages, the concept of sockets is used in different service-side languages, and the developer simply obtains a socket, You can use various methods in the socket (socket) to create a connection between different processes to achieve communication purposes. Typically, we use the following network hierarchy model,

The so-called socket (socket) is the operating system in the transport layer and the following layers of the processing of network operations are encapsulated, and then provide a socket object for us to call this object and its methods in the application to achieve the purpose of interprocess communication.

Based on the above concepts, node. JS also provides support for the socket, which provides a net module to handle TCP-related operations, provides the Dgram module to handle UDP-related operations, the difference between TCP and UDP is not covered here, is a cliché topic.

1. Create the TCP server side.

In node. js, it is easy to create a socket server with the following functions

var server=net.createserver ([Options],[listener]);

Where NET is the net module we introduced, the options parameter is optional and it is an object that contains the following two properties:

Allowhalfopen, this property defaults to False, this time how the TCP client sends a FIN packet, the server must send back a fin packet, which makes the TCP connection both ends simultaneously shut down, in which case no one can send information , and if the property is true, indicates that the TCP client sends a FIN packet, the service side does not postback, which causes the TCP client to shut down the traffic to the server, and the server can still send information to the client. In this case, if you want to close this TCP bidirectional connection completely, you need to explicitly call the end method of the service-side socket.

Pauseonconnect, this property defaults to False, when it is set to true to indicate that the TCP server is connected to the client socket transmitted data will not be read, that is, does not trigger a data event. If you need to read the data transmitted by the client, you can use the Resume method of the socket to set the socket.

The parameter listener represents a callback function after the socket is created, and it has a parameter that represents the currently created service-side socket,

function (socket) {    
// To do sth.
}

Finally, this method returns the server object that was created.

For this object, it inherits the Eventemitter class, which has several important events and methods, as follows:

The connection event, which is used to monitor the client socket connection to this TCP server, triggers

Server.on (' connection ',function(socket) {    // to do sth...});

The close event is triggered when the TCP server is shut down.

Server.on (' Close ',function() {    console.log (' TCP server closed ');});

Error event, triggering when TCP connection errors occur

The listen method is used to listen for TCP connection requests from the client.

The following is a complete example of creating a TCP server.

varNet=require (' Net ');varServer=net.createserver (function(socket) {Console.log (' Client and server connections '); Server.getconnections (function(Err,count) {Console.log ("Current number of connections is%d", Count);    }); Server.maxconnections=2; Console.log (' TCP Maximum number of connections is%d ', server.maxconnections);}); Server.on (' Error ',function(e) {if(e.code== ' Eaddrinuse ') {Console.log (' Address and port are occupied '); }}); Server.listen (, ' localhost ',function(){    //console.log (' server-side start monitoring ... ');    varaddress=server.address (); Console.log (address);});

This code creates a TCP server and designates the server to connect up to two clients, and listens on the local 2000 port waiting for the client connection, then we can use remote login (Telnet based TCP protocol) to test the server side, enter in two command line respectively

2000

The results are as follows:

When logging in using the Third command-line window, we found that we could not connect to the server because we have set up a TCP connection to the server only for a maximum of two.

2. Creating a TCP client and communicating with the client on the server

Creating a standalone client requires calling the net module's socket construction method, as follows:

var client=New net. Socket ([options]);

This constructor takes an optional parameter, which is an object that contains the following properties:

FD: Used to develop an existing socket file descriptor to create a socket;

Allowhalfopen: action Ibid.

readable and writeable, when using FD to create a socket, specifies whether the socket is read-write or not, and defaults to false.

In fact, the client is a separate socket object. This socket object usually has the following more important methods and properties:

The Connect method, which is used to connect to the specified TCP service side.

Socket.connect (Port,[host],[listener])

Write method that writes data to the socket on the other end

Socket.write (Data,[encoding],[callback])

Where data can be a string or buffer data, and if it is a string you need to specify a second parameter to specify its encoding. The third parameter is a callback function.

The following is a complete code to create a TCP client:

varNet=require (' Net ');varClient=NewNet. Socket (); Client.setencoding (' UTF8 '); Client.connect (, ' localhost ',function() {Console.log (' connected to service side '); Client.write (' Hello! '); SetTimeout (function() {Client.end (' Bye '); },10000);}); Client.on (' Error ',function(Err) {Console.log (' An error occurred with the server connection or communication, the error code is%s ', Err.code);    Client.destroy (); }); Client.on (' Data ',function(data) {Console.log (' The data sent to the server has been received: ' +( data);});

The code creates a TCP client, connects to a local 2000 port server, sends hello data to the server, then sends bye after 10 seconds, and finally shuts down the TCP client connection. and listen to its data event, and print it when it is received by the server.

A TCP server-side code corresponding to the client is as follows:

varNet=require (' Net ');varServer=net.createserver ({allowhalfopen:true}); Server.on (' Connection ',function(socket) {Console.log (' Client is already connected to server '); Socket.setencoding (' UTF8 '); Socket.on (' Data ',function(data) {Console.log (' Received the data sent by the client as: ' +data); Socket.write (' Confirm data: ' +data);    }); Socket.on (' Error ',function(Err) {Console.log (' An error occurred during communication with the client, error code%s ', Err.code);    Socket.destroy ();    }); Socket.on (' End ',function() {Console.log (' Client connection is turned off ');        Socket.end (); //exit the referral program when the client connection is all closedServer.unref ();    }); Socket.on (' Close ',function(has_error) {if(has_error) {Console.log (' The socket connection was closed because of an error ');        Server.unref (); }Else{Console.log (' Socket connection is properly closed '); }    });}); Server.getconnections (function(err,count) {if(count==2) {server.close (); }}); Server.listen (, ' localhost '); Server.on (' Close ',function() {Console.log (' TCP server is turned off ');});

The server receives the data sent by the client and sends it back, and exits the application automatically when all socket connections to the TCP server are disconnected.

Running these two pieces of code results in the following:

Service side:

Client

From the above we can see that the TCP connection-based communication has the following characteristics:

1) connection-oriented, must establish a connection before they can communicate with each other;

2) The TCP connection is one to one, that is, in TCP, a client socket connects to a server socket, and the two can communicate with each other, and the communication is bidirectional.

3) When the TCP connection is closed, it is possible to only close one side of the connection and retain unidirectional communication;

4) a specific IP plus port can connect to multiple TCP clients, or you can programmatically specify the connection limit.

3. Creating a UDP client and server

In node. js, the Dgram module is provided to handle UDP-related operations and calls, and we know that UDP is a non-connected, unreliable, but efficient transport protocol, so there is no difference between creating a TCP client and a server on a function call.

Use the Createsocket method of the Dgram module as follows:

var socket=dgram.createsocket (Type,[callback])

The method has two parameters, as follows:

Type : the kind of UDP protocol used, which can be UDP4 or UDP6, which must be

callback: The callback function after the completion of the creation, this parameter is optional. There are two parameters in the callback function

function (msg,rinfo) {    //  callback function code }

MSG is a buffer object that represents the received data, and Rinfo is also an object that represents the sender's information, which contains the following information:

Address: Sender IP

Port: Sender Ports

Family: Sender IP Address type, such as IPV4 or IPV6

Size: The number of bytes sent by the sender

After invoking the Create method, a UDP Scoket is returned, which has several important methods and events as follows:

message event, which is triggered when a message is received, as follows:

Socket.on (' message ', function (msg,rinfo) {    //  callback Code });

bind Method: Bind a port and IP to the socket as follows:

Socket.bind (Port,[address],[callback])

The listening event is triggered when the first time a UDP socket is received with data sent, as follows:

Socket.on (' Listening ', function () {    //  callback functions Code });

Send method that sends information to the specified UDP socket. As follows:

Socket.send (Buf,offset,length,port,address,[callback])

The method has six parameters, BUF is a buffer object or string, indicating the data to be sent, offset is the byte from which to start sending, length for the sending byte, port for the socket, address for the IP receiving socket , callback is a callback function, where callback is optional, and other parameters are required.

The following creates a full code for a UDP client

varDgram=require (' Dgram ');varMessage=NewBuffer (' Hello ');varClient=dgram.createsocket (' UDP4 '); client.send (Message,0,message.length,2001, "localhost",function(err,bytes) {if(err) console.log (' Data send failed '); ElseConsole.log ("sent%d bytes of data", bytes);}); Client.on ("Message",function(msg,rinfo) {Console.log ("Data sent by the server has been received%s", MSG); Console.log ("Server address information is%j", Rinfo); Client.close ();}); Client.on ("Close",function() {Console.log ("Socket port is closed");});

This code creates a client socket and sends a hello to another client, prints the data sent by the other socket, and then closes the client socket.

The following is the code for the corresponding service-side socket:

varDgram=require (' Dgram ');varServer=dgram.createsocket (' UDP4 '); Server.on ("Message",function(msg,rinfo) {Console.log (' Received the data sent by the client as ' + 'msg); Console.log ("Client address new information is%j", Rinfo); varbuff=NewBuffer ("confirmation message" +msg); Server.send (Buff,0, buff.length,rinfo.port,rinfo.address); SetTimeout (function() {server.unref (); },10000);}); Server.on ("Listening",function(){    varaddress=server.address (); Console.log ("Server starts listening, address information is%j", address);}); Server.bind (2001, ' localhost ');

The code creates a server socket, binds it to the local 2001 port, listens for its listening event, prints out the client information, prints the received client information and sends it back to the client, and exits the application after 10 seconds if all clients shut down.

As a result, the client:

Service side:

As we can see from the above, unlike TCP, we do not need to specifically create a socket listener client connection, the client does not have to go through the connection, but directly to the designated server socket to send information, which proves that the socket is not connected.

At the same time, for UDP, its no-connection feature makes it possible to one-to-one, many-to-many, a-to-many and many-to-a, this and TCP connection of a pair of a very big difference. Based on the UDP feature, we can use UDP to broadcast and multicast data.

4. Using UDP for data broadcast

In the Dgram module, use the socket's Setbroadcast method to open the socket's broadcast, as follows:

Socket.setbroadcast (flag)

Where flag defaults to false, which means no broadcasts are turned on, and true means open.

The so-called broadcast, refers to a host to the other host on the network to send data, the network of other hosts can receive, at the same time in accordance with the classification of IP address, for the A,b,c class address, its network segment of the host number 1 address is a broadcast address, we need to broadcast this data to this address, Instead of being sent directly to a host of a specified IP.

Based on the above understanding, we write a broadcast server as follows:

var dgram=require (' Dgram '); var server=dgram.createsocket ("UDP4"); Server.on ("message",function(msg) {     var buff=New Buffer ("Received client data:" +msg);    Server.setbroadcast (true);    Server.send (Buff,0,buff.length,2002, "192.168.56.255");}); Server.bind (2001, "192.168.56.1");

This code creates a server socket, binds the IP and port, accepts client data, and broadcasts the client data to the broadcast address of the network.

The client code is as follows:

var dgram=require (' Dgram '); var client=dgram.createsocket (' UDP4 '); Client.bind (2002, ' 192.168.56.2 '); var buf=New Buffer ("client"); Client.send (buf,0,buf.length,2001, ' 192.168.56.1 '); Client.on ("message",function(msg,rinfo) {    Console.log (' received server data is%s ', msg);});

This code means creating a client socket and binding IP and port to the socket, sending data to the server and printing the received data.

By running the server-side code on the local host and deploying the client code on a different host and modifying the IP address and port of the client socket, messages sent by any client are broadcast to all clients that communicate with that server.

5. Using UDP for multicast

The so-called multicast refers to any host can be added to a group, the address of this group is a special class D IP address, With a range of 224.0.0.0--239.255.255.255, the sender simply sends the sent data to a multicast address, and all hosts that join the reorganization can receive data from the sender (note that this is not all hosts on the network).

For multicast addresses, it is usually as follows:

• Local multicast address: 224.0.0.0~224.0.0.255, which is the address reserved for routing protocols and other uses.

• Reserved multicast address: 224.0.1.0~238.255.255.255, which can be used on a global scale (such as the Internet) or network protocols.

• Administrative rights multicast address: 239.0.0.0~239.255.255.255, which can be used internally by an organization, similar to a private IP address, is not available for the Internet and can limit the multicast range.

node. JS uses Addmembership to allow hosts to join the group, enabling IP multicast, as follows:

Socket.addmembership (multicastaddress, [Multicastinterface])

The first parameter of the method is the multicast address, the second parameter is optional, indicating the network interface IP address that the socket needs to join, and if not specified, it will be added to all valid network interfaces.

After a socket is joined to the multicast group, you can use Dropmembership to exit the multicast group, as follows:

Socket.dropmembership (multicastaddress, [Multicastinterface])

The following is a complete UDP server that sends multicast data

 var  dgram=require (' Dgram '  var  server=dgram.createsocket (' udp4 ' );    Server.on ( ' listening ', function   () {    Server.setmulticastttl ( 128); Server.addmembership ( ' 230.185.192.108 '  1000);  function   Broadcast () { new  Buffer (new   Date (). toLocaleString (    )); Server.send (buf,  0,buf.length,8088, ' 230.185.192.108 ' );}  

This code creates a socket server that sends multicast data, joins the multicast group 230.185.192.108, and sends the service-side time information to the group every second.

The corresponding client code is as follows:

var port=8088; var Host= "192.168.56.2"; var dgram=require (' Dgram '); var client=dgram.createsocket (' UDP4 '); Client.on (' listening ',function() {    Client.addmembership (' 230.185.192.108 ');}); Client.on (' message ',function(msg,remote) {    console.log (msg.tostring ());}); Client.bind (port,host);

The client creates a socket and binds its own port and IP to receive data sent from the server. Add it to the multicast group in the listening event.

Run the server-side code on the local host, run the client code on different network hosts and modify its IP and port to a different host's own IP and port, and all clients that join the multicast will receive the time information sent by the server.

6. Summary

In summary, in node. js, we can use the Net module to create TCP-based server and client connections and communications, and also use the Dgram module to handle UDP-based client and server-side communication.

node. JS Network Programming

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.