Node. js network programming _ node. js

Source: Internet
Author: User
Node. js uses the Google Chrome V8 engine, which has good performance and provides many system-level APIs, such as file operations and network programming. Node. js is a comprehensive background runtime that provides many functions that can be implemented by other languages for Javascript. Today, let's take a look at Nodejs's network programming Node to provide a wide range of network programming modules.

Node Module Protocol
Net TCP
Dgram UDP
Http HTTP
Https HTTPS

TCP Service events are classified into the following two types:

(1 ),Server events

For a server created through net. createServer (), it is an EventEmitter instance. Custom events include:

Listening: triggered after listen () is called to bind a port or Domain Socket. It is abbreviated as server. listen (port, listener) and passed in through the second parameter.

Connection: triggered when each client socket is connected to the server. The simple syntax is to use net. createServer () and pass the last parameter.

Close: triggered when the server is closed. after close (), the server stops accepting new socket connections, but keeps the existing connections. This event is triggered after all connections are disconnected.

Error: this event is triggered when an exception occurs on the server.

(2 ),Connection event

The server can be connected to multiple clients at the same time, which is a typical writable and readable Stream object for each connection. Stream objects can be used for communication between the server and the client. They can read data from one end through data events, or send data from one end to the other through the write () method.

Data: when one end calls write () to send data, the other end triggers the data event. The data transmitted by the event is the data sent by write ().

End: this event is triggered when any end of the connection sends FIN data.

Connect: this event is used on the client. It is triggered when the socket is successfully connected to the server.

Drain: this event is triggered when any end calls write () to send data.

Error: When an exception occurs

Close: triggered when the socket is completely closed

Timeout: when the connection is no longer active after a certain period of time, this event is triggered to notify the user that the connection is idle.

TCP has certain optimization policies for small data packets in the network: The Nagle algorithm is triggered only when the data reaches a certain amount.

UDP Service

UDP is called the user data packet Protocol and is not a connection-oriented service. In Node, UDP is only an EventEmitter instance, not a Stream instance. It has the following custom events:

(1) message: When a UDP socket listens to the NIC port and receives the message, the message Buffer object and a remote address information are triggered.

(2) listening: this event is triggered when UDP socket starts listening.

(3) close: this event is triggered when the close () method is called and no message event is triggered. To trigger the message event again, you need to bind it again.

(4) error: triggered when an exception occurs. If the exception is not thrown by the listener, the process exits.

HTTP service

The http module in Node inherits from the tcp server (net module) and can maintain connections with multiple clients. Because it does not create threads for each connection, it maintains a low memory usage, therefore, high concurrency can be achieved. The difference between HTTP and TCP services is that after keepalive is enabled, a TCP session can be used for multiple requests and responses. The TCP Service serves on the unit of connection, and the HTTP Service serves on the unit of request. The http module encapsulates the connection to request process.

The http module abstracts the reads and writes of the socket used for the connection into ServerRequest and ServerResponse objects, which correspond to the request and response operations respectively.

(1) HTTP Request

For read operations on TCP connections, the http module encapsulates them as ServerRequest objects. For example, the header part is req. method, req. url, req. headers: The report style data is abstracted as a read-only Stream object. If the business logic needs to read the data in the report style, the operation can be performed only after the data flow is complete.

(2) HTTP Response

The HTTP Response encapsulates write operations for the underlying connection and can be viewed as a writable Stream object.

Response Message Header Information Methods: res. setHeader () and res. writeHeader () can be set multiple times, but it takes effect only when the writeHeader write connection is called.

Method of reporting style: res. write () and res. end ()

(3) HTTP server events

Connection: A connection event is triggered when a TCP connection is established between the client and the server.

Request: After a TCP connection is established, the bottom layer of the http module abstracts the HTTP request and HTTP response from the data stream. When the request data is sent to the server, this event is triggered after the HTTP request header is parsed; in res. after end (), the TCP connection can be used for the next request.

Close: call server. close to stop receiving new connections. This event is triggered when all existing connections are disconnected.

CheckContinue: when some clients send large data, they first send a request with a response CT: 100-continue in the header to the server, and the service triggers this event;

Connect: triggered when the client initiates a CONNECT Request

Upgrade: when the client requests to upgrade the connection protocol, it must negotiate with the server. The client will include the Updagrade field in the request header.

ClientError: The connected client sends an error. This event is triggered when an error is sent to the server.

(4) HTTP client

The http module provides http. request (options, connect) to construct an HTTP client.

The HTTP client is similar to the server. In the ClientRequest object, its event is called response. When a ClientRequest parses a response packet, the response event is triggered after the response header is parsed, at the same time, a response object ClientResponse is transmitted for the operation, and subsequent response packets are provided as read-only streams.

(5) HTTP client events

Response: this event is triggered when the client corresponding to the request event of the server receives a response after the request is sent.

Socket: triggered when the connection established in the underlying connection pool is allocated to the current request object;

Connect: when the client sends a CONNECT request to the server, if the server responds to the status code 200, the client will trigger this event.

Upgrade: if the server responds to the 101 Switching Protocols status when the server sends an Upgrade request, the client triggers this event.

Continue: after the client initiates the keep CT: 100-continue header information to the server, it tries to send large data. If the server responds to the 100 continue status, the server triggers this event.

WebSocket Service

WebSocket was first introduced as an important feature of HTML5 and has the following advantages over HTTP:

(1) only one TCP connection is established between the client and the server, and fewer connections can be used.

(2) The WebSocket server can push data to the client, which is far more flexible and efficient than the HTTP request response mode.

(3) More lightweight protocol headers to reduce data transmission

Node does not have a library with built-in WebSocket, but the ws module of the Community encapsulates the underlying implementation of WebSocket, such as the famous socket. io

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.