NodeJS how to achieve true long connection?

What is the long connection?

Long connection, namely: keepalive enabled.

Popular talk:

Long non-connected state, communication with the server after each request is completed, the channel is closed. When the request again, you also need to re-open the channel.

If a long connection request is completed, the channel does not close within a certain time, do not need to re-open channel request again, there is the advantage that the communication efficiency.

NodeJS how to achieve true long connection?

When is it appropriate to enable long connection?

1, when the static pages on the web, such as: Html, pictures, Css, Js when the majority is recommended to enable long connection.

2, when you request a web and more dynamic, with more than database operations. Long connection should be closed, this will save memory and reduce I / O pressure.

Note: When connected to long on, when KeepAlive = On, KeepAliveTimeOut setting is actually a problem, set too short, can lead to frequent establish a connection, put pressure on the Cpu, long set, the system will accumulate unwanted Http connection , consume large amounts of memory. So, whether long connection enabled, and long connection timeout value is the number needs to be based on a different site conditions.

Long connection scenario programming NodeJS

In nodejs application development, a variety of scenarios require long connection control.

Such as: web server, web client, reverse proxy and so on.

In this example, to implement a simple reverse proxy, as follows:

NodeJS how to achieve true long connection?

Run to see the connection status:

WEB connection to the proxy server to close, i.e., short connection.

NodeJS how to achieve true long connection?

Proxy server to the client / browser, but also close, that is, short connection.

NodeJS how to achieve true long connection?

At this time, modify the code in the proxy server is connected to the web, the parameter increasing agent, keepalive set to true.

NodeJS how to achieve true long connection?

Then run:

Agent client request, the proxy connection to the client, the keep-alive have become, namely: a long connection.

NodeJS how to achieve true long connection?

Acting to web, web connection to the proxy, also have become long connection:

NodeJS how to achieve true long connection?
NodeJS how to achieve true long connection?

That this time, has achieved complete long connection.

Note that, in the course of the study, we have tried a variety of ways, such as manually set the packet header:

setHeader("connection", "keep-alive");

Keepalive settings or from the socket:

req.socket.setKeepAlive

Are null and void or to achieve the effect is incomplete, is not a complete long connection.

Guess you like

Origin www.cnblogs.com/w2sft/p/12570779.html