php中fsockopen用法實(shí)例

字號:


    本文實(shí)例講述了php中fsockopen用法。分享給大家供大家參考。
    具體實(shí)現(xiàn)方法如下:
    復(fù)制代碼 代碼如下:$fp=fsockopen(127.0.0.1,80); //打開數(shù)據(jù)流
    if(!$fp) //如果打開出錯
    {
    echo unable to openn; //輸出內(nèi)容
    }
    else //如果成功打開
    {
    fwrite($fp,get / http/1.0rnrn); //向數(shù)據(jù)流寫入內(nèi)容
    stream_set_timeout($fp,2); //進(jìn)行超時(shí)設(shè)置
    $res=fread($fp,2000); //讀取內(nèi)容
    $info=stream_get_meta_data($fp); //獲取數(shù)據(jù)流報(bào)頭
    fclose($fp); //關(guān)閉數(shù)據(jù)流
    if($info['timed_out']) //如果超時(shí)
    {
    echo 'connection timed out!'; //輸出內(nèi)容
    }
    else
    {
    echo $res; //輸出讀取內(nèi)容
    }
    }
    //實(shí)例二
    //創(chuàng)建服務(wù)端
    $socket=stream_socket_server(tcp://0.0.0.0:8000,$errno,$errstr);
    //如果創(chuàng)建失敗
    if(!$socket)
    {
    echo $errstr ($errno)<br />n;
    }
    //如果創(chuàng)建成功
    else
    {
    //接受連接
    while($conn=stream_socket_accept($socket))
    {
    //寫入數(shù)據(jù)
    fwrite($conn,'the local time is '.date('n/j/y g:i a').n);
    //關(guān)閉連接
    fclose($conn);
    }
    //關(guān)閉socket
    fclose($socket);
    }
    //
    $file=test.txt; //定義文件
    $fp=fopen($file,w); //打開數(shù)據(jù)流
    if($fp) //如果成功打開
    {
    stream_set_write_buffer($fp,0); //設(shè)置緩沖區(qū)
    fwrite($fp,$output); //寫入內(nèi)容
    fclose($fp); //關(guān)閉數(shù)據(jù)流
    }
    希望本文所述對大家的php程序設(shè)計(jì)有所幫助。