PHP Socket技術の浅い分析

1450 ワード

phpsocketSocketはTCP/IPプロトコルの伝送制御プロトコルに位置し、クライアント-サーバモードの非同期通信を提供し、すなわちクライアントがサーバにサービス要求を発行し、サーバが要求を受信した後、相応のフィードバックまたはサービスを提供する.最も基本的な例を練習しました
サーバがデータストリームを返さなければ接続状態を維持し、データストリームが送信されると、コンテンツが取得されるとすぐに接続を切断するブロック接続を使用して開始します.コードは次のとおりです.
 
  
$host = www.sohu.com; // , , ,
$page = "/index.html";
$port = 80;
$request = "GET $page HTTP/1.1\r
";
$request .= "Host: $host\r
";
//$request .= "Referer:$host\r
";
$request .= "Connection: close\r
\r
";
// 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);
?>