注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

Bioinformatics home

 
 
 

日志

 
 

php socket.class.php  

2009-07-17 09:23:13|  分类: PHP |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |
<?php

define("CONNECTED", true);
define("DISCONNECTED", false);

/**
 * Socket class
 * 
 * This class can be used to connect to external sockets and communicate with the server
 * 
 * @author Tom Reitsma <treitsma@rse.nl>
 * @version 0.6
 */
Class Socket
{
 /**
  * @var singleton $instance
  * @desc Singleton var
  */
 private static $instance;
 
 /**
  * @var resource $connection
  * @desc Connection resource
  */
 private $connection = null;
 
 /**
  * @var string $connectionState
  * @desc 
  */
 private $connectionState = DISCONNECTED;
 
 /**
  * @var int $defaultHost
  * @desc Default ip address to connect to
  */
 private $defaultHost = "10.46.236.32";
 
 /**
  * @var int $defaultPort
  * @desc Default port to connect to
  */
 private $defaultPort = 110;
 
 /**
  * @var float $defaultTimeout
  * @desc Default timeout for connection to a server
  */
 private $defaultTimeout = 10;
 
 /**
  * @var bool $persistentConnection
  * @desc Determines wether to use a persistent socket connection or not
  */
 private $persistentConnection = false;
 
 /**
  * Class constructor
  * 
  * @return void
  * @access private
  */
 private function __construct()
 {
  
 }
 
 /**
     * Singleton pattern. Returns the same instance to all callers
     *
     * @return Socket
     */
    public static function singleton()
    {
        if (self::$instance == null || ! self::$instance instanceof Socket)
        {
            self::$instance = new Socket();
        }
        return self::$instance;
    }
    
    /**
     * Connects to the socket with the given address and port
     * 
     * @return void
     */
    public function connect($serverHost=false, $serverPort=false, $timeOut=false)
    {
     $socketFunction = $this->persistentConnection ? "pfsockopen" : "fsockopen";
     
     // Check if the function parameters are set.
     // If not, use the class defaults
     if($serverHost == false)
     {
      $serverHost = $this->defaultHost;
     }
     
     if($serverPort == false)
     {
      $serverPort = $this->defaultPort;
     }
     
     if($timeOut == false)
     {
      $timeOut = $this->defaultTimeout;
     }
     
     $connection = $socketFunction($serverHost, $serverPort, $errorNumber, $errorString, $timeOut);
     $this->connection = $connection;
     
     stream_set_blocking($this->connection, 0);
     
     if($connection == false)
     {
      $this->_throwError("Connecting to {$serverHost}:{$serverPort} failed.<br>Reason: {$errorString}");
     }
     
     $this->connectionState = CONNECTED;
    }
    
    /**
     * Disconnects from the server
     * 
     * @return True on succes, false if the connection was already closed
     */
    public function disconnect()
    {
     if($this->validateConnection())
     {
      fclose($this->connection);
      $this->connectionState = DISCONNECTED;
      
      return true;
     }
     
     return false;
    }
    
    /**
     * Sends a command to the server
     * 
     * @return string Server response
     */
    public function sendCmd($command)
    {
     if($this->validateConnection())
     {
      $command .= "\r\n";
      
      $result = fwrite($this->connection, $command, strlen($command));
      
      return $result;
     }
     
     $this->_throwError("Sending command \"{$command}\" failed.<br>Reason: Not connected");
    }
    
    /**
     * Gets the server response (not multilined)
     * 
     * @return string Server response
     */
    public function getResponse()
    {
     if($this->validateConnection())
     {
      return fread($this->connection, 2048);
     }
     
     $this->_throwError("Receiving response from server failed.<br>Reason: Not connected");
    }
    
    /**
  * Gets a multilined response
  * 
  * @return string Server response
  */
 public function getMultilinedResponse()
    {
        $data = '';
        while(($tmp = $this->readLine()) != '.') 
        {
            if(substr($tmp, 0, 2) == '..') 
            {
    $tmp = substr($tmp, 1);
            }
            $data .= $tmp."\r\n";
        }

        return substr($data, 0, -2);
    }
    
    /**
     * Reads an entire line
     * 
     * @return string Server response
     */
    public function readLine() 
    {
        $line = '';
        while (!feof($this->connection))
        {
            $line .= fgets($this->connection, 1024);
            if (strlen($line) >= 2 && (substr($line, -2) == "\r\n" || substr($line, -1) == "\n")) 
            {
    return rtrim($line);
            }
        }
        return $line;
    }
    
    /**
     * Validates the connection state
     * 
     * @return bool
     */
    private function validateConnection()
    {
     return (is_resource($this->connection) && ($this->connectionState != DISCONNECTED));
    }
    
    /**
     * Throws an error
     * 
     * @return void
     */
    private function _throwError($errorMessage)
    {
     throw new Exception("Socket error: " . $errorMessage);
    }
    
    /**
     * If there still was a connection alive, disconnect it
     */
    public function __destruct()
    {
     $this->disconnect();
    }
}

?>
  评论这张
 
阅读(1166)| 评论(0)
推荐 转载

历史上的今天

在LOFTER的更多文章

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017