3 * A TCP connection listener
5 * @author Roland Haeder <webmaster@ship-simu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009, 2010 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__);
36 * Creates an instance of this class
38 * @param $nodeInstance A NodeHelper instance
39 * @return $listenerInstance An instance a prepared listener class
41 public final static function createTcpListener (NodeHelper $nodeInstance) {
43 $listenerInstance = new TcpListener();
45 // Set the application instance
46 $listenerInstance->setNodeInstance($nodeInstance);
48 // Set the protocol to TCP
49 $listenerInstance->setProtocol('tcp');
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, gettype($mainSocket), 0, 'invalid'), 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) {
77 throw new InvalidSocketException(array($this, gettype($mainSocket), $socketError, socket_strerror($socketError)), BaseListener::EXCEPTION_INVALID_SOCKET);
80 // Set the option to reuse the port
81 if (!socket_set_option($mainSocket, SOL_SOCKET, SO_REUSEADDR, 1)) {
82 // Get socket error code for verification
83 $socketError = socket_last_error($mainSocket);
86 $errorMessage = socket_strerror($socketError);
88 // Shutdown this socket
89 $this->shutdownSocket($mainSocket);
92 throw new InvalidSocketException(array($this, gettype($mainSocket), $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
95 // Now, we want non-blocking mode
96 $this->debugOutput('LISTENER: Setting non-blocking mode.');
97 if (!socket_set_nonblock($mainSocket)) {
98 // Get socket error code for verification
99 $socketError = socket_last_error($mainSocket);
102 $errorMessage = socket_strerror($socketError);
104 // Shutdown this socket
105 $this->shutdownSocket($mainSocket);
108 throw new InvalidSocketException(array($this, gettype($mainSocket), $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
111 // "Bind" the socket to the given address, on given port so this means
112 // that all connections on this port are now our resposibility to
113 // send/recv data, disconnect, etc..
114 $this->debugOutput('LISTENER: Binding to address ' . $this->getListenAddress() . ':' . $this->getListenPort());
115 if (!socket_bind($mainSocket, $this->getListenAddress(), $this->getListenPort())) {
116 // Get socket error code for verification
117 $socketError = socket_last_error($mainSocket);
120 $errorMessage = socket_strerror($socketError);
122 // Shutdown this socket
123 $this->shutdownSocket($mainSocket);
126 throw new InvalidSocketException(array($this, gettype($mainSocket), $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
129 // Start listen for connections
130 $this->debugOutput('LISTENER: Listening for connections.');
131 if (!socket_listen($mainSocket)) {
132 // Get socket error code for verification
133 $socketError = socket_last_error($mainSocket);
136 $errorMessage = socket_strerror($socketError);
138 // Shutdown this socket
139 $this->shutdownSocket($mainSocket);
142 throw new InvalidSocketException(array($this, gettype($mainSocket), $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
145 // Set the main socket
146 $this->registerServerSocketResource($mainSocket);
148 // Initialize the client pool instance
149 $poolInstance = ObjectFactory::createObjectByConfiguredName('client_pool_class', array($this));
152 $poolInstance->addClient($mainSocket);
154 // And add it to this listener
155 $this->setPoolInstance($poolInstance);
157 // Initialize iterator for listening on packages
158 $iteratorInstance = ObjectFactory::createObjectByConfiguredName('network_listen_iterator_class', array($poolInstance->getPoolEntriesInstance()));
160 // Rewind it and remember it in this class
161 $iteratorInstance->rewind();
162 $this->setIteratorInstance($iteratorInstance);
164 // Initialize the network package handler
165 $packageInstance = ObjectFactory::createObjectByConfiguredName('tcp_network_package_handler_class');
167 // Set it in this class
168 $this->setPackageInstance($packageInstance);
171 $this->debugOutput('LISTENER: TCP listener now ready on IP ' . $this->getListenAddress() . ', port ' . $this->getListenPort() . ' for service.');
175 * "Listens" for incoming network packages
179 public function doListen () {
181 $readers = $this->getPoolInstance()->getAllSockets();
185 // Check if we have some clients left
186 $left = socket_select(
194 // Some new clients found?
200 // Do we have changed clients?
201 if (in_array($this->getSocketResource(), $readers)) {
203 $newSocket = socket_accept($this->getSocketResource());
205 // We want non-blocking here, too
206 if (!socket_set_nonblock($newSocket)) {
207 // Get socket error code for verification
208 $socketError = socket_last_error($newSocket);
211 $errorMessage = socket_strerror($socketError);
213 // Shutdown this socket
214 $this->shutdownSocket($newSocket);
217 throw new InvalidSocketException(array($this, gettype($newSocket), $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
220 // Add it to the clients
221 $this->getPoolInstance()->addClient($newSocket);
224 // Do we have to rewind?
225 if (!$this->getIteratorInstance()->valid()) {
227 $this->getIteratorInstance()->rewind();
230 // Get the current value
231 $current = $this->getIteratorInstance()->current();
233 // Handle it here, if not main socket
234 if ($current != $this->getSocketResource()) {
235 // ... or else it will raise warnings like 'Transport endpoint is not connected'
236 $this->getPackageInstance()->processResourcePackage($current);
239 // Advance to next entry. This should be the last line
240 $this->getIteratorInstance()->next();