简体   繁体   中英

PHP curl timeout from node.js HTTP server

I have a simple Node.js HTTP server running (following code) where I am trying to respond to any request immediately and then process the request asynchronously.

var http = require('http');
var url = require('url');
var querystring = require('querystring');
http.createServer(function parseRequest(request, response){
    // Responding without any delay
    response.end();
    var query = url.parse(request.url).query;
    var param1 = querystring.parse(query)["param1"];
    var param2 = querystring.parse(query)["param2"];
    console.log("Param1: " + param1 + " and param2: " + param2);
}).listen(8888);
console.log("HTTP server started on port 8888");

I have another PHP script (following code) which is sending a Curl GET request to the HTTP server. I am specifying the curl connection timeout in milliseconds

<?php
$url = "http://127.0.0.1:8888?param1=value1&param2=value2";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT_MS, 1000);
$start_time = microtime();
$response = curl_exec($curl);
$stop_time = microtime();
if(curl_errno($curl) != 0)
    echo "Curl error " . curl_error($curl) . "\n";
curl_close($curl);
echo "Started at " . $start_time . " and stopped at " . $stop_time . "\n";
?>

Notice that I gave 1000 ms as connection timeout for curl and this is working fine. I get a message like the following from my PHP script.

But when I give a value less than 1000 (even 999), the curl connection times out and I get the following message

Is there any settings I am missing here? I am using and .

In looking at the PHP docs on this timeout value, you may be running into a limitation of your local system. The docs state:

If libcurl is built to use the standard system name resolver, that portion of the connect will still use full-second resolution for timeouts with a minimum timeout allowed of one second.

In setting that value below the minimum value allowed for a timeout, you may be causing the system to trigger a timeout automatically.

UPDATE: Looks like this previous question is the same issue. In order to set sub 1000ms values for this, you'll need to:

You have to compile libcurl for yourself, using --enable-threaded-resolver and then compile curl extension for php against it

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