本节分享下,php多线程的几个例子,不使用fork或进程
以下代码实现:检查正在运行的n台服务器,以确定它们正常运转。
<?php $hosts = array("host1.x.com", "host2.x.com", "host3.x.com"); $timeout = 15; $status = array(); foreach ($hosts as $host) { $errno = 0; $errstr = ""; $s = fsockopen($host, 80, $errno, $errstr, $timeout); if ($s) { $status[$host] = "Connectedn"; fwrite($s, "HEAD / HTTP/1.0rnHost: $hostrnrn"); do { $data = fread($s, 8192); if (strlen($data) == 0) { break; } $status[$host] .= $data; } while (true); fclose($s); } else { $status[$host] = "Connection failed: $errno $errstrn"; } } //by www.jb200.com print_r($status); ?>
以上代码在fsockopen()分析完hostname且建立一个成功的连接(或延时$timeout秒)之前,扩充这段代码来管理大量服务器将耗费很长时间。
放弃这段代码;可以建立异步连接-不需要等待fsockopen返回连接状态。
PHP仍然需要解析hostname(所以直接使用ip更加明智),不过将在打开一个连接之后立刻返回,继而就可以连接下一台服务器。
有两种方法可以实现;
1,PHP5中可以使用新增的stream_socket_client()函数直接替换掉fsocketopen()。
2,PHP5之前的版本,需要自己动手,用sockets进行扩展。
例子,PHP5中的解决方法:
<?php $hosts = array("host1.x.com", "host2.x.com", "host3.x.com"); $timeout = 15; $status = array(); $sockets = array(); /* Initiate connections to all the hosts simultaneously */ foreach ($hosts as $id => $host) { $s = stream_socket_client("$host:80", $errno, $errstr, $timeout, STREAM_CLIENT_ASYNC_CONNECT|STREAM_CLIENT_CONNECT); if ($s) { $sockets[$id] = $s; $status[$id] = "in progress"; } else { $status[$id] = "failed, $errno $errstr"; } } /* Now, wait for the results to come back in */ while (count($sockets)) { $read = $write = $sockets; /* This is the magic function - explained below */ $n = stream_select($read, $write, $e = null, $timeout); if ($n > 0) { /* readable sockets either have data for us, or are failed * connection attempts */ foreach ($read as $r) { $id = array_search($r, $sockets); $data = fread($r, 8192); if (strlen($data) == 0) { if ($status[$id] == "in progress") { $status[$id] = "failed to connect"; } fclose($r); unset($sockets[$id]); } else { $status[$id] .= $data; } } /* writeable sockets can accept an HTTP request */ foreach ($write as $w) { $id = array_search($w, $sockets); fwrite($w, "HEAD / HTTP/1.0rnHost: " . $hosts[$id] . "rnrn"); $status[$id] = "waiting for response"; } } else { /* timed out waiting; assume that all hosts associated * with $sockets are faulty */ foreach ($sockets as $id => $s) { $status[$id] = "timed out " . $status[$id]; } break; } //by www.jb200.com } foreach ($hosts as $id => $host) { echo "Host: $hostn"; echo "Status: " . $status[$id] . "nn"; } ?>
用stream_select()等待sockets打开的连接事件。
stream_select()调用系统的select(2)函数来工作:
前面三个参数是你要使用的streams的数组;
可以对其读取,写入和获取异常(分别针对三个参数)。
stream_select()可以通过设置$timeout(秒)参数来等待事件发生-事件发生时,相应的sockets数据将写入你传入的参数。