There is a set of tasks that need to be parallelized:
The user's search query is sent to several search engines, the results are combined and returned to the user. The idea is that requests to sites are not sequential (waiting time is critical), but parallel.
Hooked the idea of setting the task to a separate script or daemon ... then to ajax check the completion of the task . A year ago, @org, answering a question about asynchronous streams, described the logic of the work, which, in my opinion, might be useful here :
- Script A adds the task to a specific location and gives the answer that the task is in progress.
- Script B (hidden from users) takes active tasks and starts performing.
- Script A checks the status of the task (in process / completed / not executed) and responds if successful.
Points 1 and 3 are clear. But the idea of a separate script (2) or even individual scripts is not quite. In general, I will be glad to tips on possible solutions.
UPD. I pick and modify the code, which is provided on the page Development of multitasking applications for PHP v5 . I tried to add two sites. What is plugging?
<?php $timeout = 10; $result = array(); $sockets = array(); $convenient_read_block = 8192; $urls = array('ya.ru', 'google.com'); $id = 0; foreach($urls as $url) { $s = stream_socket_client($url . ":80", $errno, $errstr, $timeout, STREAM_CLIENT_ASYNC_CONNECT|STREAM_CLIENT_CONNECT); if ($s) { $sockets[$id++] = $s; fwrite($s, "GET / HTTP/1.0\r\nHost: " . $url . "\r\nAccept: */*\r\n\r\n"); } else { echo "Stream " . $id . " failed to open correctly."; } } while (count($sockets)) { $read = $sockets; stream_select($read, $w = null, $e = null, $timeout); if (count($read)) { foreach ($read as $r) { $id = array_search($r, $sockets); $data = fread($r, $convenient_read_block); if (strlen($data) == 0) { fclose($r); unset($sockets[$id]); } else { $result[$id] .= $data; } } } else { echo "Time-out!\n"; break; } } ?>