Advertisement
nuit

Socket.class

Mar 20th, 2011
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.10 KB | None | 0 0
  1. /**
  2. * Class for managing a socket
  3. */
  4.  
  5. class Socket {
  6.     /**
  7.      * handler for the socket
  8.      *
  9.      * @var resource
  10.      */
  11.     private $handler;
  12.  
  13.  
  14.     /**
  15.      * Constructor of the class...if host and port are set opens a socket
  16.      *
  17.      * @param    string    $host    host for the socket
  18.      * @param    string    $port    port for the socket
  19.      */
  20.     function __construct( $host='',$port='' ) {
  21.         if(!empty($host) AND !empty($port)) {
  22.             return $this->connect($host,$port);
  23.         }
  24.     }
  25.  
  26.  
  27.     /**
  28.      * Creates a socket to a certain host with a certain port
  29.      *
  30.      * @param    string    $host        host for the socket
  31.      * @param    string    $port        port for the socket
  32.      * @param    int        $timeout    timeout for the socket
  33.      *
  34.      * @return resource $this->handler handler for the socket or bool false
  35.      */
  36.     function connect( $host, $port,$timeout=30 ) {
  37.         $this->handler = @fsockopen( $host, $port, $errno, $errstr, $timeout );
  38.  
  39.         if($this->handler) {
  40.             return $this->handler;
  41.         } else {
  42.             return false;
  43.         }
  44.     }
  45.  
  46.    
  47.     /**
  48.      * Reads from the socket
  49.      *
  50.      * @param int $bytes Number of bytes to read from the socket...if not set it will read everything
  51.      *
  52.      * @return string $buffer The output of the socket
  53.      *
  54.      */
  55.     function read($bytes='') {
  56.         $buffer = '';
  57.         if(empty($bytes)) {
  58.             while (!feof($this->handler)) {
  59.                 $buffer .= @fgets($this->handler, 1024);
  60.             }
  61.         } else {
  62.             $buffer = @fgets($this->handler,$bytes);
  63.         }
  64.  
  65.         return $buffer;
  66.     }
  67.  
  68.    
  69.     /**
  70.      * Writes on the socket
  71.      *
  72.      * @param string $str The string you want to write on the socket
  73.      *
  74.      * @return bool always true
  75.      *
  76.      */
  77.     function send($str) {
  78.         @fwrite($this->handler,$str);
  79.        
  80.         return true;
  81.     }
  82.    
  83.    
  84.     /**
  85.      * Closes the socket handler
  86.      */
  87.     function close( ) {
  88.         @fclose($this->handler);
  89.     }
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement