Node provides a wealth of network programming modules
Node模块 | 协议 |
net | TCP |
dgram | UDP |
http | HTTP |
https | HTTPS |
TCP service events are divided into the following two categories
(1), Server event
For a server created through net.createServer(), it is an EventEmitter instance. There are the following types of custom events:
listening: Triggered after calling listen() to bind a port or Domain Socket, abbreviated as server.listen(port, listener), passed in through the second parameter.
connection: Triggered when each client socket connects to the server. The concise way to write it is through net.createServer(), and the last parameter is passed.
close: Triggered when the server is closed. After calling server.close(), the server will stop accepting new socket connections, but keep the currently existing connections. This event will be triggered after all connections are disconnected.
error: This event will be triggered when an exception occurs on the server.
(2), Connection event
The server can maintain connections with multiple clients at the same time, and is a typical writable and readable Stream object for each connection. The Stream object can be used for communication between the server and the client. It can read data from one end from the other end through the data event, or send data from one end to the other end through the write() method.
data: When one end calls write() to send data, the other end will trigger the data event, and the data passed by the event is the data sent by write()
end: This event will be triggered when either end of the connection sends FIN data.
connect: This event is used for the client and is triggered when the socket is successfully connected to the server.
drain: When either end calls write() to send data, the current end triggers this event.
error: Sent when exception
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 a certain optimization strategy for small data packets in the network: Nagle algorithm, which is triggered only when the data reaches a certain amount.
UDP Service
UDP is called User Datagram Protocol, which is not a connection-oriented service. UDP in Node is just an EventEmitter instance, not a Stream instance, and has the following custom events:
(1) message: Triggered when the UDP socket listens to the network card port and receives a message. The data carried by the trigger is the message Buffer object and a remote address information.
(2) listening: This event is triggered when the UDP socket starts listening.
(3) close: This event is triggered when the close() method is called, and the message event will no longer be triggered. If you need to trigger the message event again, you need to rebind it.
(4) error: Triggered when an exception occurs. If it is not monitored, it will be thrown directly to cause the process to exit.
HTTP service
The http module in Node is inherited from the tcp server (net module). It can maintain connections with multiple clients. Because it does not create threads for each connection and maintains very low memory usage, it can achieve high concurrency. The difference between HTTP service and TCP service is that after keepalive is turned on, a TCP session can be used for multiple requests and responses. TCP services are provided in connection units, and HTTP services are provided in request units. The http module encapsulates the process from connection to request.
The http module abstracts the reading and writing of the socket used for connection into ServerRequest and ServerResponse objects, which correspond to 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, and the message body data part is abstracted as a read-only stream object. If the business logic needs to read the data in the message body, it needs to complete the data flow before it can operate. .
(2) HTTP response
The HTTP response encapsulates the write operation of the underlying connection and can be viewed as a writable stream object.
Response message header information methods: res.setHeader() and res.writeHeader() methods, you can setHeader multiple times, but you must call writeHeader to write the connection to take effect.
Part of the message body methods: res.write() and res.end() methods
(3) HTTP server events
connection: When the client establishes a TCP connection with the server, a connection event is triggered
request: After establishing a TCP connection, 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, the event is triggered after parsing the HTTP request header; in res.end() After that, the TCP connection is available for the next request.
close: Call the server.close method 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 Expect: 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 needs to negotiate with the server, and the client will bring the Updagrade field in the request header
clientError: The connected client sends an error, and when the error is transmitted to the server, this event is triggered
(4) HTTP client
The http module provides http.request(options, connect) for constructing HTTP clients.
The HTTP client is similar to the server. In the ClientRequest object, its event is called response. When ClientRequest parses the response message, the response event is triggered as soon as the response header is parsed, and a response object ClientResponse is passed for operation. Subsequent response messages are provided as a read-only stream.
(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 issued.
socket: triggered when a connection established in the underlying connection pool is assigned to the current request object;
connect: When the client sends a CONNECT request to the server, if the server responds with a 200 status code, the client will trigger this event.
upgrade: When the client sends an Upgrade request to the server, if the server responds with 101 Switching Protocols status, the client will trigger this event.
continue: The client attempts to send larger data after sending an Expect: 100-continue header to the server. If the server responds with a 100 continue status, the server will trigger this event
WebSocket Service
WebSocket first appeared as an important feature of HTML5. Compared with HTTP, it has the following advantages:
(1) The client and server only establish one TCP connection, so 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 header, reducing data transmission
There is no built-in WebSocket library in Node, but the community’s ws module encapsulates the underlying implementation of WebSocket such as the famous socket.io