PHP 基于HTTP socket编程思路

<?php
/*
php socket编程,发送HTTP请求
要求能模拟下载,注册,登录。
*/
//HTTP请求类的接口
interface proto{
    //连接url
 funtion conn($url);
 //发送get查询
 funtion get();
 //发送post查询
 funtion post();
 //关闭连接
 funtion close();
}
class Http implements Proto{
   const CRLF = ‘rn';
   protected $errno = -1;
   protected $errstr = ”;
   protected $response = ”;
      protected $url = null;
   protected $version = ‘HTTP/1.1′;
   protected $fh = null;
      protected $line = array();
   protected $Header = array();
   protected $Body = array();
   public funtion__construct($url){
       $this->conn($url);
    $this->stHeader(‘Host:’.$this->url[‘host’]);
      //此方法负责写请求行
   protected funtion setLine($method){
       $this->line[0] = $method. ‘ ‘.$this->url[‘path’].’ ‘.$this->version;

   }
   //此方法负责写头信息
    protected funtion setLHeader($headerline){
       $this->header[] = $headerline;
   }
   //此方法负责写主体信息
    protected funtion setBody(){
   }
   //连接url
    public funtion conn($url){
        $this->url = parse_url($url);
     //判断端口
     if(!isset($this-$this->url[‘port’])){
         $this->url[‘port’] = 80;
      }
     $this->fh = fsockopen($this->url[‘host’],$this->url[‘port’],$this->errstr,3);
     }
   //构造get查询的数据
    public funtion get(){
        $this->setLine(‘GET’);
        $this->request();
     return $this->response;
    }
    //构造post查询的数据
    public funtion post(){
    }
    //真正请求
    public funtion request(){
        //把请求行,头信息,实体信息,放在一个数组里,便于拼接。
     $req = array_merge($this->line,$this->header,array(”),$this->body,array(”));
     //print_r($req);
     $req = implode(self::CRLF,$req);
     fwrite($this->fh,$req);
     while(!feof($this->fh)){
         $this->response.= fread($this->fh,1024)
      }
   $this->close();
   return $this->response;
    }
    //关闭连接
    public funtion close();
}
/*
$url = “http://news.163.com”;
$http = new Http($url);
$http->get();
*/

发表评论

电子邮件地址不会被公开。 必填项已用*标注

您可以使用这些HTML标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>