Socket.class.php
2.5 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
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
class Socket {
protected $_config = array(
'persistent' => false,
'host' => 'localhost',
'protocol' => 'tcp',
'port' => 80,
'timeout' => 30
);
public $config = array();
public $connection = null;
public $connected = false;
public $error = array();
public function __construct($config = array()) {
$this->config = array_merge($this->_config,$config);
if (!is_numeric($this->config['protocol'])) {
$this->config['protocol'] = getprotobyname($this->config['protocol']);
}
}
public function connect() {
if ($this->connection != null) {
$this->disconnect();
}
if ($this->config['persistent'] == true) {
$tmp = null;
$this->connection = @pfsockopen($this->config['host'], $this->config['port'], $errNum, $errStr, $this->config['timeout']);
} else {
$this->connection = fsockopen($this->config['host'], $this->config['port'], $errNum, $errStr, $this->config['timeout']);
}
if (!empty($errNum) || !empty($errStr)) {
$this->error($errStr, $errNum);
}
$this->connected = is_resource($this->connection);
return $this->connected;
}
public function error() {
}
public function write($data) {
if (!$this->connected) {
if (!$this->connect()) {
return false;
}
}
return fwrite($this->connection, $data, strlen($data));
}
public function read($length=1024) {
if (!$this->connected) {
if (!$this->connect()) {
return false;
}
}
if (!feof($this->connection)) {
return fread($this->connection, $length);
} else {
return false;
}
}
public function disconnect() {
if (!is_resource($this->connection)) {
$this->connected = false;
return true;
}
$this->connected = !fclose($this->connection);
if (!$this->connected) {
$this->connection = null;
}
return !$this->connected;
}
public function __destruct() {
$this->disconnect();
}
}