简体   繁体   中英

Node.js / How handle connection leak?

I wrote a server application in Node.js.

When I do lsof -p 10893 (10893 is the pid of my Node.js application), I get this:

node    10893 root   19u  IPv4 (num) 0t0    TCP ip-X.X.X.X->ip-X-X-X.X:45403 (ESTABLISHED)
node    10893 root   19u  IPv4 (num) 0t0    TCP ip-X.X.X.X->ip-X-X-X.X:58416(ESTABLISHED)

This connections are hold and never closed, just when I restart my application.

I have the following code in node.js, which as I understand, should handle this issue:

app.use(function(err, req, res, next) {
    res.setTimeout(120000);
    res.status(500).send('Unexpected error');
});

But these connection are still appears, even after 120000 ms.

How can I fix it?

Pretty sure this is a Keep-Alive issue. See this question and it's answer for details, but the gist is:

res.set("Connection", "close");

If you want that behavior for all your connections, then add it as a middleware above your routes/router:

app.use(function (req, res, next) {
    res.set("Connection", "close");
    next();
});

Also, if you want to time out the socket itself, it's a bit trickier:

var http = require('http');
var express = require('express');

var app = express();
var svr = http.createServer(app);

svr.on('connection', function (socket) {
    socket.setTimeout(120000, function () {
        this.end();
    });
});

// other middleware / routes here

app.use(function(err, req, res, next) {
    res.status(500).send('Unexpected error');
});

svr.listen(PORT);

EDIT :

Just noticed that your function is an error handler middleware (due to the presence of the err parameter). This means that the timeout would only have been set if there was an error, and not if the request completed successfully.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM