Latest web development tutorials

Node.js Net module

Node.js Net module

Node.js tool module Node.js tool module

Node.js Net module provides a number of gadgets for the underlying network communication, including the creation of client / server approach, we can be introduced into the module in the following ways:

var net = require("net")

method

No. Method & description
1 net.createServer ([options] [, connectionListener ])
Create a TCP server. ConnectionListener parameters automatically to the 'connection' event created listener.
2 net.connect (options [, connectionListener])
It returns a new 'net.Socket', and connect to the specified address and port.
When the socket established, it will trigger the 'connect' event.
3 net.createConnection (options [, connectionListener])
Create a host and host port to port TCP connection. host defaults to 'localhost'.
4 net.connect (port [, host] [ , connectListener])
Create a port for the host port and host TCP connection. host defaults to 'localhost'. Parameter connectListener will add as a listener to 'connect' event. Back 'net.Socket'.
5 net.createConnection (port [, host] [ , connectListener])
Create a port for the host port and host TCP connection. host defaults to 'localhost'. Parameter connectListener will add as a listener to 'connect' event. Back 'net.Socket'.
6 net.connect (path [, connectListener])
Create a connection to the path of the unix socket. ConnectListener parameters as a listener will be added to the 'connect' event. Back 'net.Socket'.
7 net.createConnection (path [, connectListener])
Create a connection to the path of the unix socket. Parameter connectListener will add as a listener to 'connect' event. Back 'net.Socket'.
8 net.isIP (input)
Detecting whether the input IP address. IPV4 return 4, IPV6 return 6, otherwise return 0.
9 net.isIPv4 (input)
If the address entered is IPV4, returns true, otherwise returns false.
10 net.isIPv6 (input)
If the address is entered as IPV6, returns true, otherwise returns false.

net.Server

net.Server often used to create a TCP or a local server.

No. Method & description
1 server.listen (port [, host] [ , backlog] [, callback])
Listening on the specified port and host port host ac connections. By default, the host accepts any IPv4 address (INADDR_ANY) direct connection. Port port is 0, it will assign a random port.
2 server.listen (path [, callback])
Specifies the path of the connection, start a local socket server.
3 server.listen (handle [, callback])
Connect by specifying the handle.
4 server.listen (options [, callback])
options attributes: port port, host host, and backlog, as well as optional parameters callback function, calling them together server.listen (port, [host], [backlog], [callback]). Also, the path parameter can be used to specify a UNIX socket.
5 server.close ([callback])
Server stops accepting new connections and maintain existing connections. This is an asynchronous function, when all connections end servers will shut down, and will trigger the 'close' event.
6 server.address ()
The operating system returns the bound address, protocol family name and the server port.
7 server.unref ()
If this is a server system event only one active call unref will allow the program to exit.
8 server.ref ()
And unref Conversely, if this is the only server, call the ref before being unref on the server will not allow the program exits (default behavior). If the server has been ref, ref is invoked again and will not have an impact.
9 server.getConnections (callback)
Asynchronous Gets the number of servers currently active connection. When the socket is sent to the child process after the effective; callback function has two arguments err and count.

event

No. Events & Description
1 listening
When the server calls server.listen binding triggers.
2 connection
It will be triggered when a new connection is created. socket is net.Socket instance.
3 close
It triggers the server shuts down. Note that if there is a connection, this event will not be triggered until all connections closed.
4 error
It is triggered when an error occurs. 'Close' event will be called directly following the event.

net.Socket

net.Socket object is a TCP or UNIX Socket abstraction. net.Socket examples of the realization of a duplex stream interface. They can be created in the user client (using the connect ()) use, or when they are created by the Node, and delivered to the user through the connection server events.

event

net.Socket events:

No. Events & Description
1 lookup
After a name, but before connecting to trigger this event. For UNIX sokcet NA.
2 connect
When the trigger is successfully established socket connection.
3 data
Fires when data is received.
4 end
When the socket and the other end to send FIN packet that triggered the event.
5 timeout
When the socket idle timeout triggered only show socket has been idle. The user must manually close the connection.
6 drain
When the trigger was empty when the write cache. It can be used to control the upload.
7 error
It is triggered when an error occurs.
8 close
Fires when the socket is completely closed. Had_error parameter is a Boolean value that indicates whether because transmission errors socket close.

Attributes

net.Socket provides many useful properties, easy to control socket interaction:

No. Property & Description
1 socket.bufferSize
This property shows the number of bytes to be written into the buffer.
2 socket.remoteAddress
Remote IP address string, for example: '74 .125.127.100 'or' 2001: 4860: a005 :: 68 '.
3 socket.remoteFamily
Remote IP protocol suite string, such as 'IPv4' or 'IPv6'.
4 socket.remotePort
Remote port, a digital representation, for example: 80 or 21.
5 socket.localAddress
Local interface of remote client network connection bundle upright in the local IP address of the connection string. For example, if you are listening '0.0.0.0' and the client is connected to '192.168.1.1', the value would be '192.168.1.1'.
6 socket.localPort
Local port address numbers. For example: 80 or 21.
7 socket.bytesRead
To get the number of bytes received.
8 socket.bytesWritten
The number of bytes sent.

method

No. Method & description
1 new net.Socket ([options])
We construct a new socket object.
2 socket.connect (port [, host] [ , connectListener])
Designated port and host port host, create a socket connection. Host parameter defaults to localhost. Normally no need to use net.createConnection open socket. Only you will be used to achieve their socket when.
3 socket.connect (path [, connectListener])
Open the unix socket specified path. Normally no need to use net.createConnection open socket. Only you will be used to achieve their socket when.
4 socket.setEncoding ([encoding])
Setting coding
5 socket.write (data [, encoding] [ , callback])
Transmitting data on the socket. The second parameter specifies the encoding of the string, the default is UTF8 encoding.
6 socket.end ([data] [, encoding ])
Semi-closed socket. For example, it sends a FIN packet. Server is still possible to send data.
7 socket.destroy ()
Make sure that no I / O activity on the socket. Only in case an error occurs only as needed. (Processing error, etc.).
8 socket.pause ()
Pause read data. That is, the data will not trigger event. For upload control is very useful.
9 socket.resume ()
Call the pause () after reading the data you want to restore.
10 socket.setTimeout (timeout [, callback])
socket idle for more than timeout milliseconds, the socket is set to time out.
11 socket.setNoDelay ([noDelay])
Disable Nag (Nagle) algorithm. By default TCP connections use Nag algorithm, they buffer data before sending. Sending data immediately noDelay set to true in a call socket.write () time. noDelay The default value is true.
12 socket.setKeepAlive ([enable] [, initialDelay ])
Disable / enable the long link function, and before sending the first in a long idle connections on the probe socket, optionally set the initial delay. The default is false. Setting initialDelay (ms) to set the delay last packet received and a long connection between the probe. The initialDelay set to 0, it will leave the default (or previous) value. The default value is 0.
13 socket.address ()
The operating system returns the bound address, protocol family name and the server port. The returned object has three attributes, such as {port: 12346, family: 'IPv4', address: '127.0.0.1'}.
14 socket.unref ()
If this is a server system event only one active call unref will allow the program to exit. If the server has been unref, unref is invoked again and will not have an impact.
15 socket.ref ()
And unref Conversely, if this is the only server, call the ref before being unref on the server will not allow the program exits (default behavior). If the server has been ref, ref is invoked again and will not have an impact.

Examples

Create server.js file, the code is as follows:

var net = require('net');
var server = net.createServer(function(connection) { 
   console.log('client connected');
   connection.on('end', function() {
      console.log('客户端关闭连接');
   });
   connection.write('Hello World!\r\n');
   connection.pipe(connection);
});
server.listen(8080, function() { 
  console.log('server is listening');
});

Implementation of the above server-side code:

$ node server.js
server is listening   # 服务已创建并监听 8080 端口

Open a new window, create client.js file, the code is as follows:

var net = require('net');
var client = net.connect({port: 8080}, function() {
   console.log('连接到服务器!');  
});
client.on('data', function(data) {
   console.log(data.toString());
   client.end();
});
client.on('end', function() { 
   console.log('断开与服务器的连接');
});

Implementation of the above client code:

连接到服务器!
Hello World!

断开与服务器的连接

Gif examples demonstrate

Node.js tool module Node.js tool module