3 * A TCP connection listener
5 * @author Roland Haeder <webmaster@ship-simu.org>
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
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.
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.
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/>.
24 class TcpListener extends BaseListener implements Listenable {
26 * Protected constructor
30 protected function __construct () {
31 // Call parent constructor
32 parent::__construct(__CLASS__);
34 // Set the protocol to TCP
35 $this->setProtocol('tcp');
39 * Creates an instance of this class
41 * @param $nodeInstance A NodeHelper instance
42 * @return $listenerInstance An instance a prepared listener class
44 public static final function createTcpListener (NodeHelper $nodeInstance) {
46 $listenerInstance = new TcpListener();
48 // Set the application instance
49 $listenerInstance->setNodeInstance($nodeInstance);
51 // Return the prepared instance
52 return $listenerInstance;
56 * Initializes the listener by setting up the required socket server
59 * @throws InvalidSocketException Thrown if the socket could not be initialized
61 public function initListener () {
62 // Create a streaming socket, of type TCP/IP
63 $mainSocket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
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);
71 // Get socket error code for verification
72 $socketError = socket_last_error($mainSocket);
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'));
80 throw new InvalidSocketException(array($this, $mainSocket, $socketError, socket_strerror($socketError)), BaseListener::EXCEPTION_INVALID_SOCKET);
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'));
89 // Get socket error code for verification
90 $socketError = socket_last_error($mainSocket);
93 $errorMessage = socket_strerror($socketError);
95 // Shutdown this socket
96 $this->shutdownSocket($mainSocket);
99 throw new InvalidSocketException(array($this, $mainSocket, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
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..
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'));
113 // Get socket error code for verification
114 $socketError = socket_last_error($mainSocket);
117 $errorMessage = socket_strerror($socketError);
119 // Shutdown this socket
120 $this->shutdownSocket($mainSocket);
123 throw new InvalidSocketException(array($this, $mainSocket, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
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'));
133 // Get socket error code for verification
134 $socketError = socket_last_error($mainSocket);
137 $errorMessage = socket_strerror($socketError);
139 // Shutdown this socket
140 $this->shutdownSocket($mainSocket);
143 throw new InvalidSocketException(array($this, $mainSocket, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
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'));
153 // Get socket error code for verification
154 $socketError = socket_last_error($mainSocket);
157 $errorMessage = socket_strerror($socketError);
159 // Shutdown this socket
160 $this->shutdownSocket($mainSocket);
163 throw new InvalidSocketException(array($this, $mainSocket, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
167 // Set the main socket
168 $this->registerServerSocketResource($mainSocket);
170 // Initialize the peer pool instance
171 $poolInstance = ObjectFactory::createObjectByConfiguredName('node_pool_class', array($this));
174 $poolInstance->addPeer($mainSocket);
176 // And add it to this listener
177 $this->setPoolInstance($poolInstance);
179 // Initialize iterator for listening on packages
180 $iteratorInstance = ObjectFactory::createObjectByConfiguredName('network_listen_iterator_class', array($poolInstance->getPoolEntriesInstance()));
182 // Rewind it and remember it in this class
183 $iteratorInstance->rewind();
184 $this->setIteratorInstance($iteratorInstance);
186 // Initialize the network package handler
187 $handlerInstance = ObjectFactory::createObjectByConfiguredName('tcp_raw_data_handler_class');
189 // Set it in this class
190 $this->setHandlerInstance($handlerInstance);
193 $this->debugOutput('TCP-LISTENER: TCP listener now ready on IP ' . $this->getListenAddress() . ', port ' . $this->getListenPort() . ' for service.');
197 * "Listens" for incoming network packages
200 * @throws InvalidSocketException If an invalid socket resource has been found
202 public function doListen () {
204 $readers = $this->getPoolInstance()->getAllSockets();
208 // Check if we have some peers left
209 $left = socket_select(
217 // Some new peers found?
223 // Do we have changed peers?
224 if (in_array($this->getSocketResource(), $readers)) {
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
232 $newSocket = socket_accept($this->getSocketResource());
233 /* NOISY-DEBUG: */ $this->debugOutput('TCP-LISTENER: newSocket=' . $newSocket);
235 // Array for timeout settings
238 'sec' => $this->getConfigInstance()->getConfigEntry('tcp_socket_accept_wait_sec'),
240 'usec' => $this->getConfigInstance()->getConfigEntry('tcp_socket_accept_wait_usec')
243 // Set timeout to configured seconds
244 // @TODO Does this work on Windozer boxes???
245 if (!socket_set_option($newSocket, SOL_SOCKET, SO_RCVTIMEO, $options)) {
246 // Handle this socket error with a faked recipientData array
247 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
250 // Output result (only for debugging!)
252 $option = socket_get_option($newSocket, SOL_SOCKET, SO_RCVTIMEO);
253 $this->debugOutput('SO_RCVTIMEO[' . gettype($option) . ']=' . print_r($option, true));
256 // Enable SO_OOBINLINE
257 if (!socket_set_option($newSocket, SOL_SOCKET, SO_OOBINLINE ,1)) {
258 // Handle this socket error with a faked recipientData array
259 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
263 if (!socket_set_nonblock($newSocket)) {
264 // Handle this socket error with a faked recipientData array
265 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
268 // Add it to the peers
269 $this->getPoolInstance()->addPeer($newSocket);
272 // Do we have to rewind?
273 if (!$this->getIteratorInstance()->valid()) {
275 $this->getIteratorInstance()->rewind();
278 // Get the current value
279 $currentSocket = $this->getIteratorInstance()->current();
281 // Handle it here, if not main socket
282 if ($currentSocket != $this->getSocketResource()) {
283 // ... or else it will raise warnings like 'Transport endpoint is not connected'
284 /* NOISY-DEBUG: */ $this->debugOutput('TCP-LISTENER: currentSocket=' . $currentSocket . ',server=' . $this->getSocketResource());
285 $this->getHandlerInstance()->processRawDataFromResource($currentSocket);
288 // Advance to next entry. This should be the last line
289 $this->getIteratorInstance()->next();
293 * Checks whether the listener would accept the given package data array
295 * @param $packageData Raw package data
296 * @return $accepts Whether this listener does accept
298 public function ifListenerAcceptsPackageData (array $packageData) {
299 $this->debugBackTrace('This call should not happen. Please report it.');