有时php cURL无法连接到Node js服务器,返回http代码0

时间:2014-03-13 05:12:50

标签: php node.js http curl redis

[上下文]     这是我本地计算机上的Node js代码,在更改主机名的实时工作正常。我永远用它来执行它。另外php代码连接到节点js服务器以进行http响应。以上组合在很大程度上适用于生产。      问题:3-4天后,节点js连接失败,导致我的应用程序停机。它返回http代码0.因为我永远使用它,它会在5-7分钟后自动连接回来,但在这段时间内它显然是痛苦的。特别是在生产上。有人可以建议我调试的潜在区域或任何有效的解决方案吗? [背景]

var config = require('./config.js'),
    http = require('http'),
    redis = require('redis'),
    redisClient = redis.createClient(config.redis.port,config.redis.host),
    url = require('url'),
    crypto = require('crypto');


var app = http.createServer(function (req, res) {
    if(req.method == "OPTIONS"){
         res.header('Access-Control-Allow-Origin', '*:*');
         res.send(200);
    } else {

        var u = url.parse(req.url,true),
            body = '';

        req.on('data',function(chunk) {
            body += chunk;
        });

        req.on('end',function() {
            if(body) {
                var data =JSON.parse(body);
                if(data.__app_secret__ && data.__app_secret__ == '12345') {
                    switch(u.pathname) {
                        case '/generateusersecret' :
                            redisClient.get(req.headers.host + '_' + data.user_id,function(err,reply) {
                                if(reply) {
                                    jsonResponse(res,{userSecret : reply});
                                } else {
                                    genToken(req.headers.host + '_' + data.user_id,res);
                                }
                            });
                        break;
                        case '/getusersecret' :
                            redisClient.get(req.headers.host + '_' + data.user_id,function(err,reply) {
                                jsonResponse(res,{userSecret : reply});
                            });
                        break;
                        case '/publish':
                            redisClient.publish(data.channel,data.message);
                            jsonResponse(res,{});
                        break;
                        default :
                            jsonResponse(res,{error : "Unknown Command: " + u.pathname});
                        break
                    }
                } else {
                    res.writeHead(403, {'Content-Type': 'text/plain'});
                    res.end('Not authorized');
                }
            }
        });
    }
});

//app.listen(config.port || 4000, "127.0.0.1");
    app.listen(6006, 'myproductionurl.com');`enter code here`
    console.log('Server running at http://myproductionurl.com:6006/');

var io = require('socket.io').listen(app,{
        'origins' : "*:*"
            }),
    sockets = {};
/*
    var io = require('socket.io').listen(6006);
    var sockets = {};
*/


io.configure(function() {
    // set authorization
    io.set('authorization',function(handshakeData,callback) {
        if(handshakeData.query.secret) {
            // when the user's secret is in redis then we trust him as an authenticated user
            if(redisClient.get(handshakeData.query.secret)) {
                callback(null,true);
            } else {
                // unauthenticated user  
                callback(null,false);
            }
        } else {
            // no secret were given
            callback('Bad URL');
        }
    });
});

// @TODO: create separeta namespaces as: /notificaions, /chat etc...
io.sockets.on('connection',function(socket) {
    var secret = socket.manager.handshaken[socket.id].query.secret,
        _redisClient = redis.createClient(config.redis.port,config.redis.host);

    // when the redis client gets a message from the subscribed channels, we are sending back to the user's browser via socket.io
    _redisClient.on('message',function(channel,message) {
        socket.emit('notification',JSON.parse(message));
    });

    // subscribe to the user's own channel
    _redisClient.subscribe(secret);
    // subscribe to the broadcast channel
    _redisClient.subscribe('broadcast');

    // TODO: subscribe to group channels (a.k.a rooms)
});


function jsonResponse(res,obj) {
    res.writeHead(200, {'Content-Type': 'application/json'});
    res.end(JSON.stringify(obj));
}

function genToken(prefix,res) {
    crypto.randomBytes(48,function(ex,buf) {
        var token = buf.toString('base64').replace(/\//g,'_').replace(/\+/g,'-');

        redisClient.get(token,function(err,reply) {
            if(reply) {
                genToken(prefix,res);
            } else {
                redisClient.set(prefix,token);
                jsonResponse(res,{userSecret : token});
            }
        });
    });

}





 private function api($url,$data) {
        $ch = curl_init();

        $data['__app_secret__'] = $this->appSecret;

        curl_setopt($ch,CURLOPT_URL, $this->apiUrl.$url);
        curl_setopt($ch,CURLOPT_POSTFIELDS, CJSON::encode($data));
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);

        $response = curl_exec($ch);

        $responseHttpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if($responseHttpCode == 403) {
            throw new CException('Your app secret is not valid');
        } elseif($responseHttpCode == 200) {
            // nop
        } else {
            throw new CException('Uknown Error: ' . $responseHttpCode );
        }

        //close connection
        curl_close($ch);

        return CJSON::decode($response);
    }

0 个答案:

没有答案