Httpcws.class.php 2.76 KB
<?php

class Util_Server_Adapter_Ws_Httpcws implements Util_Server_Adapter_Interface 
{
    const SECTION = 'httpcws'; //配置文件中有关配置段
    const PRENAME = 'servers'; //配置段中的名称
	
	/**
	 * 分词配置
	 * 
	 * @var string
	 */
	private $_config = '';
	
	/**
	 * 构造函数
	 */
	public function __construct($options = null) 
	{
		$this->_config = Util_Common_Core::loadWs();
	}
	
	/**
	 * 读取服务器列表,配置中格式:192.168.4.133:6001,192.168.4.134:6001
	 *
	 * @return array
	 */
	public function loadServers() 
	{
		$svrobj = Util_Common_Core::loadConfig ( $this->_config, self::SECTION );
		return $this->_getServersFromString ( str_replace ( ' ', '', $svrobj->{self::PRENAME} ) );
	}
	
	/**
	 * 得到可用文件服务器的配置host, port列表
	 *
	 * @return array or false
	 */
	public function loadBalanceServer() 
	{
	    $return = false;
		$servers = $this->loadServers();
		if (! empty($servers)) 
		{
		    $return = $this->_getValidServer($servers);
		}
        return $return;
	}
	
	/**
	 * 测试服务器配置数组是否格式正常
	 *
	 * @param array $ary
	 * @return boolean
	 */
	private function _checkSvrAry(array $ary)
	{
		return isset ( $ary ['host'] ) && isset ( $ary ['port'] );
	}
	
	/**
	 * 得到有效的服务器,通过fsocket检测IP和端口
	 *
	 * @param array $servers
	 * @return array | false
	 */
	private function _getValidServer($servers)
	{
		$server = false;
		$counter = count($servers);
		if (($rdm = rand ( 1, $counter )) && Util_Server_Adapter_CheckServer::check ( $servers [$rdm - 1] ['host'], $servers [$rdm - 1] ['port'] ) === true)
		{
			$server = $servers [$rdm - 1];
		}
		else if ($counter > 1)
		{
			for ($i = 1; $i <= $counter; $i++)
			{
    			if (true === Util_Server_Adapter_CheckServer::check ( $servers [$i - 1] ['host'], $servers [$i - 1] ['port'] ))
    			{
    				$server = $servers [$i - 1];
    				break;
    			}
			}
		}
		if (empty($server))
		{
		    throw new Util_Server_Exception ( '分词服务器全挂了!' );
		}
		return $server;
	}
	
	/**
	 * 分析取得的服务器字符串,得到服务器配置数组
	 *
	 * @param string $svrstring
	 * @return array
	 */
	private function _getServersFromString($svrstring) 
	{
		if ($svrstring == '')
		{
			throw new Util_Server_Exception ( get_class ( $this ) . ':服务器配置字符串为空!' );
		}
		$tmpary = array_unique ( explode ( ',', $svrstring ) );
		if (count ( $tmpary ) == 0)
		{
			throw new Util_Server_Exception ( get_class ( $this ) . ':服务器配置字符串格式错误' );
		}
		$return = array ();
		$counter = count ( $tmpary );
		for ($i = 0; $i < $counter; $i ++) 
		{
			if (($tmp = parse_url ( $tmpary [$i] )) !== false && $this->_checkSvrAry ( $tmp ))
			{
				$return [] = $tmp;
			}
		}
		return $return;
	}

}