1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10: 11:
12:
13: namespace Pry\Net;
14:
15: 16: 17: 18: 19: 20: 21: 22:
23: class Socket
24: {
25:
26: const CONNECTED = 1;
27:
28:
29: const DISCONNECTED = 0;
30:
31: 32: 33: 34:
35: protected $host = "";
36:
37: 38: 39: 40:
41: protected $port = 0;
42:
43: 44: 45: 46:
47: protected $timeout = 5;
48:
49: 50: 51: 52:
53: protected $socket = null;
54:
55: 56: 57: 58:
59: protected $state = 0;
60:
61: 62: 63: 64:
65: protected $isBlocking = false;
66:
67: 68: 69: 70: 71:
72: public function __construct($blocking = true)
73: {
74: $this->isBlocking = $blocking;
75: \Pry\Net\Exception\Handler::initialize();
76: $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
77: }
78:
79: 80: 81: 82: 83: 84: 85: 86:
87: public function connect($host, $port, $timeout = 15)
88: {
89: $this->host = $host;
90: $this->port = $port;
91: $this->timeout = $timeout;
92: if (!empty($this->socket) && is_resource($this->socket))
93: {
94:
95: socket_set_option($this->socket, SOL_SOCKET, SO_RCVTIMEO, array(
96: 'sec' => $this->timeout,
97: 'usec' => 0)
98: );
99:
100: socket_set_option($this->socket, SOL_SOCKET, SO_SNDTIMEO, array(
101: 'sec' => $this->timeout,
102: 'usec' => 0)
103: );
104:
105: $connect = socket_connect($this->socket, $this->host, $this->port);
106: if (!$connect)
107: {
108: socket_close($this->socket);
109: throw new \RuntimeException('Can\'t connect to ' . $this->host . ':' . $this->port . '.
110: Reason : ' . socket_strerror(socket_last_error()));
111: }
112: }
113: else
114: {
115: return false;
116: }
117:
118: $this->state = self::CONNECTED;
119: return true;
120: }
121:
122: 123: 124: 125:
126: public function disconnect()
127: {
128: if ($this->isConnected())
129: {
130: socket_close($this->socket);
131: $this->state = self::DISCONNECTED;
132: return true;
133: }
134:
135: return false;
136: }
137:
138: 139: 140: 141: 142: 143:
144: public function write($buffer)
145: {
146: if ($this->isConnected())
147: {
148: return socket_write($this->socket, $buffer, strlen($buffer));
149: }
150: throw new \InvalidArgumentException('No active connection');
151: }
152:
153: 154: 155: 156: 157: 158:
159: public function read($size = 2048)
160: {
161: if ($this->isConnected())
162: {
163: $datas = socket_read($this->socket, $size, PHP_BINARY_READ);
164: if ($datas !== false)
165: {
166: return $datas;
167: }
168: else
169: {
170: Throw new \RuntimeException("Lecture impossible : " . socket_strerror(socket_last_error($this->socket)));
171: }
172:
173: return false;
174: }
175: }
176:
177: 178: 179: 180:
181: public function isConnected()
182: {
183: return (is_resource($this->socket) && $this->state == self::CONNECTED);
184: }
185:
186: public function __destruct()
187: {
188: \Pry\Net\Exception\Handler::uninitialize();
189: }
190:
191: }
192: