Created
February 2, 2014 13:47
-
-
Save hirak/8768681 to your computer and use it in GitHub Desktop.
CURLOPT_FILEでHTTPレスポンスをファイルに直接書き込んでいくサンプル ref: http://qiita.com/Hiraku/items/9fb7a0df060e0424921d
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var http = require('http'); | |
http.createServer(function(req, res){ | |
var i = 0; | |
var id = 100 * Math.random() | 0; | |
res.writeHead(200, {'Content-Type': 'text/plain'}); | |
setInterval(function(){ | |
var result = id + ':' + ++i; | |
console.log(result); | |
res.write(result + '\n'); | |
}, 1000); | |
}).listen(1337, 'localhost'); | |
console.log('Server running at http://localhost:1337/'); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
const TIMEOUT = 10; | |
$mh = curl_multi_init(); | |
$ch1 = curl_init('http://localhost:1337/'); | |
$fh1 = fopen('result1.txt', 'w'); | |
curl_setopt($ch1, CURLOPT_FILE, $fh1); | |
curl_multi_add_handle($mh, $ch1); | |
$ch2 = curl_init('http://localhost:1337/'); | |
$fh2 = fopen('result2.txt', 'w'); | |
curl_setopt($ch2, CURLOPT_FILE, $fh2); | |
curl_multi_add_handle($mh, $ch2); | |
//curl_multi start | |
do $stat = curl_multi_exec($mh, $running); | |
while ($stat === CURLM_CALL_MULTI_PERFORM); | |
if (!$running || $stat !== CURLM_OK) { | |
throw new RuntimeException("$running $stat"); | |
} | |
//curl_multi wait | |
do switch (curl_multi_select($mh, TIMEOUT)) { | |
case -1: // selectに失敗するケースがあるらしい https://bugs.php.net/bug.php?id=61141 | |
usleep(10); | |
do $stat = curl_multi_exec($mh, $running); | |
while ($stat === CURLM_CALL_MULTI_PERFORM); | |
continue 2; | |
case 0: //timeout | |
continue 2; | |
default: | |
//何か変化があった | |
do $stat = curl_multi_exec($mh, $running); | |
while ($stat === CURLM_CALL_MULTI_PERFORM); | |
//強制書き込み | |
fflush($fh1); | |
fflush($fh2); | |
} while ($running); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment