]> git.mxchange.org Git - hub.git/blob - application/hub/main/helper/connection/class_BaseConnectionHelper.php
4c68a02512540e21ae54a98b593cdadce9136a74
[hub.git] / application / hub / main / helper / connection / class_BaseConnectionHelper.php
1 <?php
2 /**
3  * A general ConnectionHelper class
4  *
5  * @author              Roland Haeder <webmaster@ship-simu.org>
6  * @version             0.0.0
7  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2011 Hub Developer Team
8  * @license             GNU GPL 3.0 or any newer version
9  * @link                http://www.ship-simu.org
10  *
11  * This program is free software: you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation, either version 3 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
23  */
24 class BaseConnectionHelper extends BaseHubHelper implements Registerable, ProtocolHandler {
25         /**
26          * Protocol used
27          */
28         private $protocol = 'invalid';
29
30         /**
31          * Port number used
32          */
33         private $port = 0;
34
35         /**
36          * (IP) Adress used
37          */
38         private $address = 0;
39
40         /**
41          * Sent data in bytes
42          */
43         private $sentData = 0;
44
45         /**
46          * Offset
47          */
48         private $offset = 0;
49
50         /**
51          * Connect retries for this connection
52          */
53         private $retryCount = 0;
54
55         /**
56          * Wether this connection is shutted down
57          */
58         private $shuttedDown = false;
59
60         /**
61          * Currently sent chunks
62          */
63         private $sentChunks = array();
64
65         /**
66          * Current final hash
67          */
68         private $currentFinalHash = '';
69
70         /**
71          * Protected constructor
72          *
73          * @param       $className      Name of the class
74          * @return      void
75          */
76         protected function __construct ($className) {
77                 // Call parent constructor
78                 parent::__construct($className);
79
80                 // Register this connection helper
81                 Registry::getRegistry()->addInstance('connection', $this);
82         }
83
84         /**
85          * Getter for port number to satify ProtocolHandler
86          *
87          * @return      $port   The port number
88          */
89         public final function getPort () {
90                 return $this->port;
91         }
92
93         /**
94          * Setter for port number to satify ProtocolHandler
95          *
96          * @param       $port   The port number
97          * @return      void
98          */
99         protected final function setPort ($port) {
100                 $this->port = $port;
101         }
102
103         /**
104          * Getter for protocol
105          *
106          * @return      $protocol       Used protocol
107          */
108         public final function getProtocol () {
109                 return $this->protocol;
110         }
111
112         /**
113          * Setter for protocol
114          *
115          * @param       $protocol       Used protocol
116          * @return      void
117          */
118         protected final function setProtocol ($protocol) {
119                 $this->protocol = $protocol;
120         }
121
122         /**
123          * Getter for IP address
124          *
125          * @return      $address        The IP address
126          */
127         public final function getAddress () {
128                 return $this->address;
129         }
130
131         /**
132          * Setter for IP address
133          *
134          * @param       $address        The IP address
135          * @return      void
136          */
137         protected final function setAddress ($address) {
138                 $this->address = $address;
139         }
140
141         /**
142          * "Accept" a visitor by simply calling it back
143          *
144          * @param       $visitorInstance        A Visitor instance
145          * @return      void
146          */
147         protected final function accept (Visitor $visitorInstance) {
148                 // Just call the visitor
149                 $visitorInstance->visitConnectionHelper($this);
150         }
151
152         /**
153          * "Getter" for raw data from a package array. A fragmenter is used which
154          * will returns us only so many raw data which fits into the back buffer.
155          * The rest is being held in a back-buffer and waits there for the next
156          * cycle and while be then sent.
157          *
158          * This method does 4 simple steps:
159          * 1) Aquire fragmenter object instance from the factory
160          * 2) Handle over the package data array to the fragmenter
161          * 3) Request a chunk
162          * 4) Finally return the chunk (array) to the caller
163          *
164          * @param       $packageData    Raw package data array
165          * @return      $rawDataChunk   An array with the raw data as value and chunk hash as key
166          */
167         private function getRawDataFromPackageArray (array $packageData) {
168                 // If there is no fragmenter?
169                 if (!Registry::getRegistry()->instanceExists('package_fragmenter')) {
170                         // Get the fragmenter instance
171                         $fragmenterInstance = ObjectFactory::createObjectByConfiguredName('package_fragmenter_class');
172
173                         // Add it to the registry
174                         Registry::getRegistry()->addInstance('package_fragmenter', $fragmenterInstance);
175                 } else {
176                         // Get fragmenter from registry
177                         $fragmenterInstance = Registry::getRegistry()->getInstance('package_fragmenter');
178                 }
179
180                 // Implode the package data array and fragement the resulting string, returns the final hash
181                 $this->currentFinalHash = $fragmenterInstance->fragmentPackageArray($packageData, $this);
182
183                 // Get the next raw data chunk from the fragmenter
184                 $rawDataChunk = $fragmenterInstance->getNextRawDataChunk($this->currentFinalHash);
185
186                 // Return it
187                 return $rawDataChunk;
188         }
189
190         /**
191          * Sends raw package data to the recipient
192          *
193          * @param       $packageData    Raw package data
194          * @return      $sentBytes              Actual sent bytes to the peer
195          * @throws      InvalidSocketException  If we got a problem with this socket
196          */
197         public function sendRawPackageData (array $packageData) {
198                 // Convert the package data array to a raw data stream
199                 $rawDataChunk = $this->getRawDataFromPackageArray($packageData);
200
201                 // Get socket resource
202                 $socketResource = $this->getSocketResource();
203
204                 // And deliver it
205                 $sentBytes = @socket_write($socketResource, $rawData, $this->getConfigInstance()->getConfigEntry($this->getProtocol() . '_buffer_length') - $this->offset);
206
207                 // If there was an error, we don't continue here
208                 if ($sentBytes === false) {
209                         // Get socket error code for verification
210                         $socketError = socket_last_error($socketResource);
211
212                         // Get error message
213                         $errorMessage = socket_strerror($socketError);
214
215                         // Shutdown this socket
216                         $this->shutdownSocket($socketResource);
217
218                         // And throw it
219                         throw new InvalidSocketException(array($this, gettype($socketResource), $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
220                 } // END - if
221
222                 // The difference between sent bytes and length of raw data should not be below zero
223                 assert((strlen($rawData) - $sentBytes) >= 0);
224
225                 // Return sent bytes
226                 return $sentBytes;
227         }
228
229         /**
230          * Getter for real class name
231          *
232          * @return      $class  Name of this class
233          */
234         public function __toString () {
235                 // Class name representation
236                 $class = $this->getAddress() . ':' . $this->getPort() . ':' . parent::__toString();
237
238                 // Return it
239                 return $class;
240         }
241
242         /**
243          * Checks wether the connect retry is exhausted
244          *
245          * @return      $isExhaused             Wether connect retry is exchausted
246          */
247         public final function isConnectRetryExhausted () {
248                 // Construct config entry
249                 $configEntry = $this->getProtocol() . '_connect_retry_max';
250
251                 // Check it out
252                 $isExhausted = ($this->retryCount >=  $this->getConfigInstance()->getConfigEntry($configEntry));
253
254                 // Return it
255                 return $isExhausted;
256         }
257
258         /**
259          * Increases the connect retry count
260          *
261          * @return      void
262          */
263         public final function increaseConnectRetry () {
264                 $this->retryCount++;
265         }
266
267         /**
268          * Marks this connection as shutted down
269          *
270          * @return      void
271          */
272         protected final function markConnectionShutdown () {
273                 $this->shuttedDown = true;
274         }
275
276         /**
277          * Getter for shuttedDown
278          *
279          * @return      $shuttedDown    Wether this connection is shutted down
280          */
281         public final function isShuttedDown () {
282                 return $this->shuttedDown;
283         }
284 }
285
286 // [EOF]
287 ?>