PHP網(wǎng)絡(luò)函數(shù)fsockopen如何實現(xiàn)Socket鏈接
PHP既然被許多網(wǎng)站作為網(wǎng)站建設(shè)的主要高級語言,當(dāng)然少不了與網(wǎng)絡(luò)有關(guān)的函數(shù)。我們今天將會給大家?guī)鞵HP網(wǎng)絡(luò)函數(shù)fsockopen在實現(xiàn)Socket鏈接時的具體用法,希望能對大家有所幫助。
#t#語法: int fsockopen(string hostname, int port, int [errno], string [errstr], int [timeout]);
返回值: 整數(shù)
函數(shù)種類: 網(wǎng)絡(luò)系統(tǒng)內(nèi)容說明: 目前PHP網(wǎng)絡(luò)函數(shù)fsockopen提供二個 Socket 資料流界面,分別為 Internet 用的 AF_INET 及 Unix 用的 AF_UNIX。當(dāng)在 Internet 情形下使用時,參數(shù) hostname 及 port 分別代表網(wǎng)址及埠號。在 UNIX 情形可做 IPC,hostname 參數(shù)表示到 socket 的路徑,port 配置為 0??墒÷缘?timeout 選項表示多久沒有連上就中斷。在使用本函數(shù)之后會返回文件指針,供文件函數(shù)使用,包括 fgets()、fgetss()、fputs()、fclose() 與 feof()。參數(shù) errno 及 errstr 也是可省略的,主要當(dāng)做錯誤處理使用。使用本函數(shù),會使用擱置模式 (blocking mode) 處理,可用set_socket_blocking() 轉(zhuǎn)換成無擱置模式。
PHP網(wǎng)絡(luò)函數(shù)fsockopen的使用范例,本例用來模擬成 HTTP 連接。
- <?php
- $fp = fsockopen("php.wilson.gs", 80, &$errno, &$errstr, 10);
- if(!$fp) {
- echo "$errstr ($errno)<br>n";
- } else {
- fputs($fp,"GET / HTTP/1.0nHost: php.wilson.gsnn");
- while(!feof($fp)) {
- echo fgets($fp,128);
- }
- fclose($fp);
- }
- ?>
通過上面這段PHP網(wǎng)絡(luò)函數(shù)fsockopen的使用示例,讀者朋友們是不是已經(jīng)能夠基本掌握了這個函數(shù)的用法了呢?