3 * An UDP 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 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->setProtocolName('udp');
39 * Creates an instance of this class
41 * @return $listenerInstance An instance a prepared listener class
43 public static final function createUdpListener () {
45 $listenerInstance = new UdpListener();
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 is invalid or an
58 public function initListener () {
59 // Try to open a UDP socket
60 $mainSocket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
62 // Is the socket a valid resource or do we have any error?
63 if (!is_resource($mainSocket)) {
64 // Then throw an InvalidSocketException
65 throw new InvalidSocketException(array($this, $mainSocket), BaseListener::EXCEPTION_INVALID_SOCKET);
69 * "Bind" the socket to the given address, on given port so this means
70 * that all connections on this port are now our resposibility to
71 * send/recv data, disconnect, etc..
73 self::createDebugInstance(__CLASS__)->debugOutput('UDP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: Binding to address ' . $this->getListenAddress() . ':' . $this->getListenPort());
74 if (!socket_bind($mainSocket, $this->getListenAddress(), $this->getListenPort())) {
75 // Handle the socket error with a faked recipientData array
76 $this->handleSocketError(__METHOD__, __LINE__, $mainSocket, array('0.0.0.0', '0'));
78 // Get socket error code for verification
79 $socketError = socket_last_error($mainSocket);
82 $errorMessage = socket_strerror($socketError);
84 // Shutdown this socket
85 $this->shutdownSocket($mainSocket);
88 throw new InvalidSocketException(array($this, $mainSocket, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
92 // Now, we want non-blocking mode
93 self::createDebugInstance(__CLASS__)->debugOutput('UDP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: Setting non-blocking mode.');
94 if (!socket_set_nonblock($mainSocket)) {
95 // Handle the socket error with a faked recipientData array
96 $this->handleSocketError(__METHOD__, __LINE__, $mainSocket, array('0.0.0.0', '0'));
98 // Get socket error code for verification
99 $socketError = socket_last_error($socket);
102 $errorMessage = socket_strerror($socketError);
104 // Shutdown this socket
105 $this->shutdownSocket($mainSocket);
108 throw new InvalidSocketException(array($this, $mainSocket, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
112 // Set the option to reuse the port
113 self::createDebugInstance(__CLASS__)->debugOutput('UDP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: Setting re-use address option.');
114 if (!socket_set_option($mainSocket, SOL_SOCKET, SO_REUSEADDR, 1)) {
115 // Handle the socket error with a faked recipientData array
116 $this->handleSocketError(__METHOD__, __LINE__, $mainSocket, array('0.0.0.0', '0'));
118 // Get socket error code for verification
119 $socketError = socket_last_error($mainSocket);
122 $errorMessage = socket_strerror($socketError);
124 // Shutdown this socket
125 $this->shutdownSocket($mainSocket);
128 throw new InvalidSocketException(array($this, $mainSocket, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
132 // Remember the socket in our class
133 $this->registerServerSocketResource($mainSocket);
135 // Initialize the network package handler
136 $handlerInstance = ObjectFactory::createObjectByConfiguredName('udp_raw_data_handler_class');
138 // Set it in this class
139 $this->setHandlerInstance($handlerInstance);
142 self::createDebugInstance(__CLASS__)->debugOutput('UDP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: UDP listener now ready on IP ' . $this->getListenAddress() . ', port ' . $this->getListenPort() . ' for service.');
146 * "Listens" for incoming network packages
151 public function doListen() {
152 // Read a package and determine the peer
153 $amount = @socket_recvfrom($this->getSocketResource(), $rawData, $this->getConfigInstance()->getConfigEntry('udp_buffer_length'), MSG_DONTWAIT, $peer, $port);
156 $lastError = socket_last_error($this->getSocketResource());
158 // Do we have an error at the line?
159 if ($lastError == 11) {
161 * This (resource temporary unavailable) can be safely ignored on
162 * "listening" UDP ports. If we don't clear the error here, our UDP
163 * "listener" won't read any packages except if the UDP sender
164 * starts the transmission before this "listener" came up...
166 socket_clear_error($this->getSocketResource());
168 // Skip further processing
170 } elseif ($lastError > 0) {
171 // Other error detected
172 self::createDebugInstance(__CLASS__)->debugOutput('UDP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: Error detected: ' . socket_strerror($lastError));
174 // Skip further processing
176 } elseif ((empty($rawData)) || (trim($peer) == '')) {
177 // Zero sized packages/peer names are usual in non-blocking mode
182 self::createDebugInstance(__CLASS__)->debugOutput('UDP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: Handling UDP package with size ' . strlen($rawData) . ' from peer ' . $peer . ':' . $port);
186 * Checks whether the listener would accept the given package data array
188 * @param $packageData Raw package data
189 * @return $accepts Whether this listener does accept
191 function ifListenerAcceptsPackageData (array $packageData) {
192 $this->partialStub('This call should not happen. Please report it.');