]> git.mxchange.org Git - hub.git/blob - application/hub/main/listener/tcp/class_TcpListener.php
0ad6eccd683f41c5609329fbdcbfe478c35dab97
[hub.git] / application / hub / main / listener / tcp / class_TcpListener.php
1 <?php
2 /**
3  * A TCP connection listener
4  *
5  * @author              Roland Haeder <webmaster@ship-simu.org>
6  * @version             0.0.0
7  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2012 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 TcpListener extends BaseListener implements Listenable {
25         /**
26          * Protected constructor
27          *
28          * @return      void
29          */
30         protected function __construct () {
31                 // Call parent constructor
32                 parent::__construct(__CLASS__);
33
34                 // Set the protocol to TCP
35                 $this->setProtocol('tcp');
36         }
37
38         /**
39          * Creates an instance of this class
40          *
41          * @param       $nodeInstance           A NodeHelper instance
42          * @return      $listenerInstance       An instance a prepared listener class
43          */
44         public static final function createTcpListener (NodeHelper $nodeInstance) {
45                 // Get new instance
46                 $listenerInstance = new TcpListener();
47
48                 // Set the application instance
49                 $listenerInstance->setNodeInstance($nodeInstance);
50
51                 // Return the prepared instance
52                 return $listenerInstance;
53         }
54
55         /**
56          * Initializes the listener by setting up the required socket server
57          *
58          * @return      void
59          * @throws      InvalidSocketException  Thrown if the socket could not be initialized
60          */
61         public function initListener () {
62                 // Create a streaming socket, of type TCP/IP
63                 $mainSocket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
64
65                 // Is the socket resource valid?
66                 if (!is_resource($mainSocket)) {
67                         // Something bad happened
68                         throw new InvalidSocketException(array($this, $mainSocket), BaseListener::EXCEPTION_INVALID_SOCKET);
69                 } // END - if
70
71                 // Get socket error code for verification
72                 $socketError = socket_last_error($mainSocket);
73
74                 // Check if there was an error else
75                 if ($socketError > 0) {
76                         // Handle this socket error with a faked recipientData array
77                         $this->handleSocketError(__METHOD__, __LINE__, $mainSocket, array('0.0.0.0', '0'));
78                         /*
79                         // Then throw again
80                         throw new InvalidSocketException(array($this, $mainSocket, $socketError, socket_strerror($socketError)), BaseListener::EXCEPTION_INVALID_SOCKET);
81                         */
82                 } // END - if
83
84                 // Set the option to reuse the port
85                 if (!socket_set_option($mainSocket, SOL_SOCKET, SO_REUSEADDR, 1)) {
86                         // Handle this socket error with a faked recipientData array
87                         $this->handleSocketError(__METHOD__, __LINE__, $mainSocket, array('0.0.0.0', '0'));
88                         /*
89                         // Get socket error code for verification
90                         $socketError = socket_last_error($mainSocket);
91
92                         // Get error message
93                         $errorMessage = socket_strerror($socketError);
94
95                         // Shutdown this socket
96                         $this->shutdownSocket($mainSocket);
97
98                         // And throw again
99                         throw new InvalidSocketException(array($this, $mainSocket, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
100                         */
101                 } // END - if
102
103                 /*
104                  * "Bind" the socket to the given address, on given port so this means
105                  * that all connections on this port are now our resposibility to
106                  * send/recv data, disconnect, etc..
107                  */
108                 $this->debugOutput('TCP-LISTENER: Binding to address ' . $this->getListenAddress() . ':' . $this->getListenPort());
109                 if (!socket_bind($mainSocket, $this->getListenAddress(), $this->getListenPort())) {
110                         // Handle this socket error with a faked recipientData array
111                         $this->handleSocketError(__METHOD__, __LINE__, $mainSocket, array('0.0.0.0', '0'));
112                         /*
113                         // Get socket error code for verification
114                         $socketError = socket_last_error($mainSocket);
115
116                         // Get error message
117                         $errorMessage = socket_strerror($socketError);
118
119                         // Shutdown this socket
120                         $this->shutdownSocket($mainSocket);
121
122                         // And throw again
123                         throw new InvalidSocketException(array($this, $mainSocket, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
124                         */
125                 } // END - if
126
127                 // Start listen for connections
128                 $this->debugOutput('TCP-LISTENER: Listening for connections.');
129                 if (!socket_listen($mainSocket)) {
130                         // Handle this socket error with a faked recipientData array
131                         $this->handleSocketError(__METHOD__, __LINE__, $mainSocket, array('0.0.0.0', '0'));
132                         /*
133                         // Get socket error code for verification
134                         $socketError = socket_last_error($mainSocket);
135
136                         // Get error message
137                         $errorMessage = socket_strerror($socketError);
138
139                         // Shutdown this socket
140                         $this->shutdownSocket($mainSocket);
141
142                         // And throw again
143                         throw new InvalidSocketException(array($this, $mainSocket, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
144                         */
145                 } // END - if
146
147                 // Now, we want non-blocking mode
148                 $this->debugOutput('TCP-LISTENER: Setting non-blocking mode.');
149                 if (!socket_set_nonblock($mainSocket)) {
150                         // Handle this socket error with a faked recipientData array
151                         $this->handleSocketError(__METHOD__, __LINE__, $mainSocket, array('0.0.0.0', '0'));
152                         /*
153                         // Get socket error code for verification
154                         $socketError = socket_last_error($mainSocket);
155
156                         // Get error message
157                         $errorMessage = socket_strerror($socketError);
158
159                         // Shutdown this socket
160                         $this->shutdownSocket($mainSocket);
161
162                         // And throw again
163                         throw new InvalidSocketException(array($this, $mainSocket, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
164                         */
165                 } // END - if
166
167                 // Set the main socket
168                 $this->registerServerSocketResource($mainSocket);
169
170                 // Initialize the peer pool instance
171                 $poolInstance = ObjectFactory::createObjectByConfiguredName('node_pool_class', array($this));
172
173                 // Add main socket
174                 $poolInstance->addPeer($mainSocket);
175
176                 // And add it to this listener
177                 $this->setPoolInstance($poolInstance);
178
179                 // Initialize iterator for listening on packages
180                 $iteratorInstance = ObjectFactory::createObjectByConfiguredName('network_listen_iterator_class', array($poolInstance->getPoolEntriesInstance()));
181
182                 // Rewind it and remember it in this class
183                 $iteratorInstance->rewind();
184                 $this->setIteratorInstance($iteratorInstance);
185
186                 // Initialize the network package handler
187                 $handlerInstance = ObjectFactory::createObjectByConfiguredName('tcp_raw_data_handler_class');
188
189                 // Set it in this class
190                 $this->setHandlerInstance($handlerInstance);
191
192                 // Output message
193                 $this->debugOutput('TCP-LISTENER: TCP listener now ready on IP ' . $this->getListenAddress() . ', port ' . $this->getListenPort() . ' for service.');
194         }
195
196         /**
197          * "Listens" for incoming network packages
198          *
199          * @return      void
200          * @throws      InvalidSocketException  If an invalid socket resource has been found
201          */
202         public function doListen () {
203                 // Get all readers
204                 $readers = $this->getPoolInstance()->getAllSockets();
205                 $writers = array();
206                 $excepts = array();
207
208                 // Check if we have some peers left
209                 $left = socket_select(
210                         $readers,
211                         $writers,
212                         $excepts,
213                         0,
214                         150
215                 );
216
217                 // Some new peers found?
218                 if ($left < 1) {
219                         // Nothing new found
220                         return;
221                 } // END - if
222
223                 // Do we have changed peers?
224                 if (in_array($this->getSocketResource(), $readers)) {
225                         /*
226                          * Then accept it, if this socket is set to non-blocking IO and the
227                          * connection is NOT sending any data, socket_read() may throw
228                          * error 11 (Resource temporary unavailable). This really nasty
229                          * because if you have blocking IO socket_read() will wait and wait
230                          * and wait ...
231                          */
232                         $newSocket = socket_accept($this->getSocketResource());
233
234                         // Debug message
235                         /* NOISY-DEBUG: */ $this->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: newSocket=' . $newSocket . ',server=' .$this->getSocketResource());
236
237                         // Array for timeout settings
238                         $options  = array(
239                                 // Seconds
240                                 'sec'  => $this->getConfigInstance()->getConfigEntry('tcp_socket_accept_wait_sec'),
241                                 // Milliseconds
242                                 'usec' => $this->getConfigInstance()->getConfigEntry('tcp_socket_accept_wait_usec')
243                         );
244
245                         // Set timeout to configured seconds
246                         // @TODO Does this work on Windozer boxes???
247                         if (!socket_set_option($newSocket, SOL_SOCKET, SO_RCVTIMEO, $options)) {
248                                 // Handle this socket error with a faked recipientData array
249                                 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
250                         } // END - if
251
252                         // Output result (only for debugging!)
253                         /*
254                         $option = socket_get_option($newSocket, SOL_SOCKET, SO_RCVTIMEO);
255                         $this->debugOutput('SO_RCVTIMEO[' . gettype($option) . ']=' . print_r($option, true));
256                         */
257
258                         // Enable SO_OOBINLINE
259                         if (!socket_set_option($newSocket, SOL_SOCKET, SO_OOBINLINE ,1)) {
260                                 // Handle this socket error with a faked recipientData array
261                                 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
262                         } // END - if
263
264                         // Set non-blocking
265                         if (!socket_set_nonblock($newSocket)) {
266                                 // Handle this socket error with a faked recipientData array
267                                 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
268                         } // END - if
269
270                         // Add it to the peers
271                         $this->getPoolInstance()->addPeer($newSocket);
272
273                         // Get peer name
274                         if (!socket_getpeername($newSocket, $peerName)) {
275                                 // Handle this socket error with a faked recipientData array
276                                 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
277                         } // END - if
278
279                         // Create a faked package data array
280                         $packageData = array(
281                                 NetworkPackage::PACKAGE_DATA_SENDER    => $peerName . ':0',
282                                 NetworkPackage::PACKAGE_DATA_RECIPIENT => $this->getSessionId(),
283                                 NetworkPackage::PACKAGE_DATA_PROTOCOL  => $this->getProtocol(),
284                                 NetworkPackage::PACKAGE_DATA_STATUS    => NetworkPackage::PACKAGE_STATUS_FAKED
285                         );
286
287                         // Get a socket registry
288                         $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
289
290                         // Register the socket with the registry and with the faked array
291                         $registryInstance->registerSocket($this, $newSocket, $packageData);
292                 } // END - if
293
294                 // Do we have to rewind?
295                 if (!$this->getIteratorInstance()->valid()) {
296                         // Rewind the list
297                         $this->getIteratorInstance()->rewind();
298                 } // END - if
299
300                 // Get the current value
301                 $currentSocket = $this->getIteratorInstance()->current();
302
303                 // Handle it here, if not main socket
304                 /* NOISY-DEBUG: */ $this->debugOutput('TCP-LISTENER: currentSocket=' . $currentSocket . ',server=' . $this->getSocketResource());
305                 if ($currentSocket != $this->getSocketResource()) {
306                         // ... or else it will raise warnings like 'Transport endpoint is not connected'
307                         $this->getHandlerInstance()->processRawDataFromResource($currentSocket);
308                 } // END - if
309
310                 // Advance to next entry. This should be the last line
311                 $this->getIteratorInstance()->next();
312         }
313
314         /**
315          * Checks whether the listener would accept the given package data array
316          *
317          * @param       $packageData    Raw package data
318          * @return      $accepts                Whether this listener does accept
319          */
320         public function ifListenerAcceptsPackageData (array $packageData) {
321                 $this->debugBackTrace('This call should not happen. Please report it.');
322         }
323 }
324
325 // [EOF]
326 ?>