3 * A TCP connection listener
5 * @author Roland Haeder <webmaster@shipsimu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2015 Hub Developer Team
8 * @license GNU GPL 3.0 or any newer version
9 * @link http://www.shipsimu.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->setProtocolName('tcp');
39 * Creates an instance of this class
41 * @return $listenerInstance An instance a prepared listener class
43 public static final function createTcpListener () {
45 $listenerInstance = new TcpListener();
47 // Return the prepared instance
48 return $listenerInstance;
52 * Initializes the listener by setting up the required socket server
55 * @throws InvalidSocketException Thrown if the socket could not be initialized
57 public function initListener () {
58 // Create a streaming socket, of type TCP/IP
59 $mainSocket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
61 // Is the socket resource valid?
62 if (!is_resource($mainSocket)) {
63 // Something bad happened
64 throw new InvalidSocketException(array($this, $mainSocket), BaseListener::EXCEPTION_INVALID_SOCKET);
67 // Get socket error code for verification
68 $socketError = socket_last_error($mainSocket);
70 // Check if there was an error else
71 if ($socketError > 0) {
72 // Handle this socket error with a faked recipientData array
73 $this->handleSocketError(__METHOD__, __LINE__, $mainSocket, array('0.0.0.0', '0'));
76 throw new InvalidSocketException(array($this, $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 // Handle this socket error with a faked recipientData array
83 $this->handleSocketError(__METHOD__, __LINE__, $mainSocket, array('0.0.0.0', '0'));
85 // Get socket error code for verification
86 $socketError = socket_last_error($mainSocket);
89 $errorMessage = socket_strerror($socketError);
91 // Shutdown this socket
92 $this->shutdownSocket($mainSocket);
95 throw new InvalidSocketException(array($this, $mainSocket, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
100 * "Bind" the socket to the given address, on given port so this means
101 * that all connections on this port are now our resposibility to
102 * send/recv data, disconnect, etc..
104 self::createDebugInstance(__CLASS__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: Binding to address ' . $this->getListenAddress() . ':' . $this->getListenPort());
105 if (!socket_bind($mainSocket, $this->getListenAddress(), $this->getListenPort())) {
106 // Handle this socket error with a faked recipientData array
107 $this->handleSocketError(__METHOD__, __LINE__, $mainSocket, array('0.0.0.0', '0'));
109 // Get socket error code for verification
110 $socketError = socket_last_error($mainSocket);
113 $errorMessage = socket_strerror($socketError);
115 // Shutdown this socket
116 $this->shutdownSocket($mainSocket);
119 throw new InvalidSocketException(array($this, $mainSocket, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
123 // Start listen for connections
124 self::createDebugInstance(__CLASS__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: Listening for connections.');
125 if (!socket_listen($mainSocket)) {
126 // Handle this socket error with a faked recipientData array
127 $this->handleSocketError(__METHOD__, __LINE__, $mainSocket, array('0.0.0.0', '0'));
129 // Get socket error code for verification
130 $socketError = socket_last_error($mainSocket);
133 $errorMessage = socket_strerror($socketError);
135 // Shutdown this socket
136 $this->shutdownSocket($mainSocket);
139 throw new InvalidSocketException(array($this, $mainSocket, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
143 // Now, we want non-blocking mode
144 self::createDebugInstance(__CLASS__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: Setting non-blocking mode.');
145 if (!socket_set_nonblock($mainSocket)) {
146 // Handle this socket error with a faked recipientData array
147 $this->handleSocketError(__METHOD__, __LINE__, $mainSocket, array('0.0.0.0', '0'));
149 // Get socket error code for verification
150 $socketError = socket_last_error($mainSocket);
153 $errorMessage = socket_strerror($socketError);
155 // Shutdown this socket
156 $this->shutdownSocket($mainSocket);
159 throw new InvalidSocketException(array($this, $mainSocket, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
163 // Set the main socket
164 $this->registerServerSocketResource($mainSocket);
166 // Initialize the peer pool instance
167 $poolInstance = ObjectFactory::createObjectByConfiguredName('node_pool_class', array($this));
170 $poolInstance->addPeer($mainSocket, BaseConnectionHelper::CONNECTION_TYPE_SERVER);
172 // And add it to this listener
173 $this->setPoolInstance($poolInstance);
175 // Initialize iterator for listening on packages
176 $iteratorInstance = ObjectFactory::createObjectByConfiguredName('network_listen_iterator_class', array($poolInstance->getPoolEntriesInstance()));
178 // Rewind it and remember it in this class
179 $iteratorInstance->rewind();
180 $this->setIteratorInstance($iteratorInstance);
182 // Initialize the network package handler
183 $handlerInstance = ObjectFactory::createObjectByConfiguredName('tcp_raw_data_handler_class');
185 // Set it in this class
186 $this->setHandlerInstance($handlerInstance);
189 self::createDebugInstance(__CLASS__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: TCP listener now ready on IP ' . $this->getListenAddress() . ', port ' . $this->getListenPort() . ' for service.');
193 * "Listens" for incoming network packages
197 public function doListen () {
199 $this->doListenSocketSelect(':0');
203 * Checks whether the listener would accept the given package data array
205 * @param $packageData Raw package data
206 * @return $accepts Whether this listener does accept
207 * @throws UnsupportedOperationException If this method is called
209 public function ifListenerAcceptsPackageData (array $packageData) {
210 // Please don't call this
211 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);