nodejs http服务器超时

时间:2018-11-21 16:18:25

标签: node.js nodes

我已经建立了一个节点js http服务器,如果请求的时间超过一个周期,则需要自动发送答案。我需要停止该过程,因为我希望为其他请求释放资源。我已经成功获得了自动答案,但是在我的日志中,我仍然跟踪到代码仍将执行到最后...该怎么办?

这是我的代码示例:

function processWithQueries(path, params, res) {
        switch (path) {
            case '/join' : 
                mountjoin(params, res);
                break;
            case '/left' : 
                mountleft(params, res);
                break;
            ....
            default:
                illegal(path, params, res);
        }

}
var server = http.createServer(function (req, res) {
    try {
        var body = '';
        var myreq = '';
        var path = '';
        var data = null;

        res.setTimeout(maxtimeout, function(){
            res.writeHead(200, {'custom-header': 1, 'Access-Control-Allow-Origin': '*'});
            res.end();
            accesslogger.info(os.hostname() + ' [200] path ' + path + ' req timeout ' + maxtimeout + 'ms exceeded', data);
            req.socket.destroy();
            return;
        });
        host = req.headers.host.split(':');
        if (host[0] != 'localhost') {
            applogger.error(os.hostname() + ' no local host');
            res.writeHead(403);
            res.end('Forbidden');
        } else {
            if (req.method == 'POST') {
                req.on('data', function (data) {
                    body += data;
                    if (body.length > 40000) { // FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
                        applogger.error(os.hostname() + ' FLOOD ATTACK OR FAULTY CLIENT', body);
                        req.connection.destroy();
                        res.writeHead(500);
                        res.end('Internal Server Error');
                    }
                });
                req.on('end', function () {
                    myreq = url.parse(req.url, true);
                    path = myreq.pathname;
                    data = qs.parse(body);
                    processWithQueries(path, data, res);
                });
            } else if (req.method == 'GET') { // for tests only
                myreq = url.parse(req.url, true);
                path = myreq.pathname;
                data = myreq.query;
                processWithQueries(path, data, res);
            } else {
                illegal(res);
            }
        }
    } catch (err) {
        res.writeHead(200, {'custom-header': 1, 'Access-Control-Allow-Origin': '*'});
        res.end();
        applogger.error(os.hostname() + ' Icecasttreatment exception', err);
        accesslogger.info(os.hostname() + ' [200] exception but auth sent', err);
    }
}).on('error', function (err) {
    applogger.error(os.hostname() + ' server error', err);
}).listen(listenport);

捕获代码永远不会发生,也不会出现错误情况。但是,像mountjoin和mountleft之类的功能已完全执行,但应该中断。

0 个答案:

没有答案