Question

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.

Started at 0.57268300 1386132518 and stopped at 0.58577100 1386132518

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

Curl error Timeout was reached

Started at 0.55238500 1386131950 and stopped at 0.55245800 1386131950

Is there any settings I am missing here? I am using php 5.4.6 and curl 7.27.0.

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top