Httpcws.class.php
2.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
<?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;
}
}