淺析PHP Socket技術_PHP教程

來源:互聯網
上載者:User
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協議的傳輸控制通訊協定,提供客戶-伺服器模式的非同步通訊,即客戶向伺服器發出服務要求,伺服器接收到請求後,提供相...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.