phpsocketSocket位於TCP/IP協議的傳輸控制通訊協定,提供客戶-伺服器模式的非同步通訊,即客戶向伺服器發出服務要求,伺服器接收到請求後,提供相應的反饋或服務!我練習了一個最基本的例子:
使用並發起一個阻塞式(block)串連,即伺服器如果不返回資料流,則一直保持串連狀態,一旦有資料流傳入,取得內容後就立即中斷連線。代碼如下:
複製代碼 代碼如下:
$host = www.sohu.com; //這個地址隨便,用新浪的也行,主要是測試用,哪個無所謂
$page = "/index.html";
$port = 80;
$request = "GET $page HTTP/1.1\r\n";
$request .= "Host: $host\r\n";
//$request .= "Referer:$host\r\n";
$request .= "Connection: close\r\n\r\n";
//允許串連的逾時時間為1.5秒
$connectionTimeout = 1.5;
//允許遠程伺服器2秒鐘內完成回應
$responseTimeout = 2;
//建立一個socket串連
$fp = fsockopen($host, $port, $errno, $errstr, $connectionTimeout);
if (!$fp) {
throw new Exception("Connection to $hostfailed:$errstr");
} else {
stream_set_blocking($fp, true);
stream_set_timeout($fp, $responseTimeout);
}
//發送請求字串
fwrite($fp, $request);
//取得返回的資料流內容
$content = stream_get_contents($fp);
echo $content;
$meta = stream_get_meta_data($fp);
if ($meta['timed_out']) {
throw new Exception("Responsefrom web services server timed out.");
}
//關閉Socket串連
fclose($fp);
?>
http://www.bkjia.com/PHPjc/328092.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/328092.htmlTechArticlephpsocketSocket位於TCP/IP協議的傳輸控制通訊協定,提供客戶-伺服器模式的非同步通訊,即客戶向伺服器發出服務要求,伺服器接收到請求後,提供相...