有关fsockopen相关随笔

测试环境,从本机(windows)访问内外一台linux服务器(此服务器装的是nginx)

服务器上的index.php如下:

<?php
     echo 1;

?> 


1.使用Http1.1协议请求

 

function asyn_sendmail() {
     $ip = '192.168.1.45';
     $url = '/index.php';
     $fp =  fsockopen( $ip, 80,  $errno$errstr, 5);
     if (! $fp) {
         echo " $errstr ( $errno)<br />\n";
    }

     $end = "\r\n";
     $input = "GET  $url HTTP/1.1 $end";
    // 如果不加下面这一句,会返回一个http400错误   

    //$input.="Host: $ip$end";

    //如果不加下面这一句,请求会阻塞很久  

    //$input.="Connection: Close$end"; 

    $input.="$end";
    fputs($fp$input);
    $html = '';
    while (!feof($fp)) {
        $html.=fgets($fp);
    }
    fclose($fp);
    writelog($html);
    echo $html;
}

function writelog($message) {
    $path = 'D:\log.txt';
    $handler = fopen($path, 'w+b');
    if ($handler) {
        $success = fwrite($handler$message);
        fclose($handler);
    }
}

asyn_sendmail();  

 

 如果注释了$input.="Host: $ip$end";这一句,则会得到一个404错误,D:\log.txt内容如下:

HTTP/1.1 400 Bad Request
Server: nginx/0.8.46
Date: Fri, 30 Dec 2011 02:11:45 GMT
Content-Type: text/html
Content-Length: 173
Connection: close

< html >
< head >< title >400 Bad Request </ title ></ head >
< body  bgcolor ="white" >
< center >< h1 >400 Bad Request </ h1 ></ center >
< hr >< center >nginx/0.8.46 </ center >
</ body >
</ html > 

说明使用http1.1连接,则必须加上Host请求表头

如果加上了没有注释$input.="Host: $ip$end";这一句 ,则请求成功,D:\log.txt内容如下:

HTTP/1.1 200 OK 

Server: nginx/0.8.46
Date: Fri, 30 Dec 2011 02:20:49 GMT
Content-Type: text/html
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept-Encoding
X-Powered-By: PHP/5.3.8

1
0
0

 返回成功,但是不明白为什么服务器返回内容多了2个0(后来网上查询资料发现,这是因为服务器使用了chunked输出所致,用Wireshark抓包可清晰看到其细节)。如果不加$input.="Connection: Close$end";这一句 ,则Http请求会阻塞很久(在这一句fgets($fp)阻塞)

 

 

2.不指定Http版本

<?php
function asyn_sendmail() {
    $ip = '192.168.1.45';
    $url = '/servertimmer/inserttopicshow/13990/AA8AB76B-7280-578F-12F2-F423685FBD26';
    $fp = fsockopen($ip, 80, $errno, $errstr, 5);
    if (!$fp) {
        echo "$errstr ($errno)<br />\n";
    }
    $end = "\r\n";
    $input = "GET $url$end";   
    $input.="$end";
    fputs($fp, $input);
    $html = '';
    while (!feof($fp)) {
        $html.=fgets($fp);
    }
    fclose($fp);
    writelog($html);
    echo $html;
}
function writelog($message) {
    $path = 'D:\log.txt';
    $handler = fopen($path, 'w+b');
    if ($handler) {
        $success = fwrite($handler, $message);
        fclose($handler);
    }
}
asyn_sendmail();
?>  

 

 请求立刻返回,没有阻塞,返回内容如下:

 1

 注意,返回内容中没有http标头,且没有被阻塞。

 

 

转载于:https://www.cnblogs.com/mxw09/archive/2011/12/30/2307019.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值