3 * An UDP connection listener
5 * @author Roland Haeder <webmaster@shipsimu.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.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 UdpListener extends BaseListener implements Listenable {
26 * Protected constructor
30 protected function __construct () {
31 // Call parent constructor
32 parent::__construct(__CLASS__);
34 // Set the protocol to UDP
35 $this->setProtocol('udp');
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 createUdpListener (NodeHelper $nodeInstance) {
46 $listenerInstance = new UdpListener();
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 is invalid or an
62 public function initListener () {
63 // Try to open a UDP socket
64 $mainSocket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
66 // Is the socket a valid resource or do we have any error?
67 if (!is_resource($mainSocket)) {
68 // Then throw an InvalidSocketException
69 throw new InvalidSocketException(array($this, $mainSocket), BaseListener::EXCEPTION_INVALID_SOCKET);
73 * "Bind" the socket to the given address, on given port so this means
74 * that all connections on this port are now our resposibility to
75 * send/recv data, disconnect, etc..
77 self::createDebugInstance(__CLASS__)->debugOutput('UDP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: Binding to address ' . $this->getListenAddress() . ':' . $this->getListenPort());
78 if (!socket_bind($mainSocket, $this->getListenAddress(), $this->getListenPort())) {
79 // Handle the socket error with a faked recipientData array
80 $this->handleSocketError(__METHOD__, __LINE__, $mainSocket, array('0.0.0.0', '0'));
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, $mainSocket, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
96 // Now, we want non-blocking mode
97 self::createDebugInstance(__CLASS__)->debugOutput('UDP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: Setting non-blocking mode.');
98 if (!socket_set_nonblock($mainSocket)) {
99 // Handle the socket error with a faked recipientData array
100 $this->handleSocketError(__METHOD__, __LINE__, $mainSocket, array('0.0.0.0', '0'));
102 // Get socket error code for verification
103 $socketError = socket_last_error($socket);
106 $errorMessage = socket_strerror($socketError);
108 // Shutdown this socket
109 $this->shutdownSocket($mainSocket);
112 throw new InvalidSocketException(array($this, $mainSocket, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
116 // Set the option to reuse the port
117 self::createDebugInstance(__CLASS__)->debugOutput('UDP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: Setting re-use address option.');
118 if (!socket_set_option($mainSocket, SOL_SOCKET, SO_REUSEADDR, 1)) {
119 // Handle the socket error with a faked recipientData array
120 $this->handleSocketError(__METHOD__, __LINE__, $mainSocket, array('0.0.0.0', '0'));
122 // Get socket error code for verification
123 $socketError = socket_last_error($mainSocket);
126 $errorMessage = socket_strerror($socketError);
128 // Shutdown this socket
129 $this->shutdownSocket($mainSocket);
132 throw new InvalidSocketException(array($this, $mainSocket, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
136 // Remember the socket in our class
137 $this->registerServerSocketResource($mainSocket);
139 // Initialize the network package handler
140 $handlerInstance = ObjectFactory::createObjectByConfiguredName('udp_raw_data_handler_class');
142 // Set it in this class
143 $this->setHandlerInstance($handlerInstance);
146 self::createDebugInstance(__CLASS__)->debugOutput('UDP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: UDP listener now ready on IP ' . $this->getListenAddress() . ', port ' . $this->getListenPort() . ' for service.');
150 * "Listens" for incoming network packages
155 public function doListen() {
156 // Read a package and determine the peer
157 $amount = @socket_recvfrom($this->getSocketResource(), $rawData, $this->getConfigInstance()->getConfigEntry('udp_buffer_length'), MSG_DONTWAIT, $peer, $port);
160 $lastError = socket_last_error($this->getSocketResource());
162 // Do we have an error at the line?
163 if ($lastError == 11) {
165 * This (resource temporary unavailable) can be safely ignored on
166 * "listening" UDP ports. If we don't clear the error here, our UDP
167 * "listener" won't read any packages except if the UDP sender
168 * starts the transmission before this "listener" came up...
170 socket_clear_error($this->getSocketResource());
172 // Skip further processing
174 } elseif ($lastError > 0) {
175 // Other error detected
176 self::createDebugInstance(__CLASS__)->debugOutput('UDP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: Error detected: ' . socket_strerror($lastError));
178 // Skip further processing
180 } elseif ((empty($rawData)) || (trim($peer) == '')) {
181 // Zero sized packages/peer names are usual in non-blocking mode
186 self::createDebugInstance(__CLASS__)->debugOutput('UDP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: Handling UDP package with size ' . strlen($rawData) . ' from peer ' . $peer . ':' . $port);
190 * Checks whether the listener would accept the given package data array
192 * @param $packageData Raw package data
193 * @return $accepts Whether this listener does accept
195 function ifListenerAcceptsPackageData (array $packageData) {
196 $this->partialStub('This call should not happen. Please report it.');