]> git.mxchange.org Git - hub.git/blob - application/hub/classes/listener/udp/class_UdpListener.php
This interface can be moved to 'core' + removed parameter nodeInstance.
[hub.git] / application / hub / classes / listener / udp / class_UdpListener.php
1 <?php
2 /**
3  * An UDP connection listener
4  *
5  * @author              Roland Haeder <webmaster@shipsimu.org>
6  * @version             0.0.0
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
10  *
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.
15  *
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.
20  *
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/>.
23  */
24 class UdpListener extends BaseListener implements Listenable {
25         /**
26          * Protected constructor
27          *
28          * @return      void
29          */
30         protected function __construct () {
31                 // Call parent constructor
32                 parent::__construct(__CLASS__);
33
34                 // Set the protocol to UDP
35                 $this->setProtocolName('udp');
36         }
37
38         /**
39          * Creates an instance of this class
40          *
41          * @return      $listenerInstance       An instance a prepared listener class
42          */
43         public static final function createUdpListener () {
44                 // Get new instance
45                 $listenerInstance = new UdpListener();
46
47                 // Return the prepared instance
48                 return $listenerInstance;
49         }
50
51         /**
52          * Initializes the listener by setting up the required socket server
53          *
54          * @return      void
55          * @throws      InvalidSocketException  Thrown if the socket is invalid or an
56          *                                                                      error was detected.
57          */
58         public function initListener () {
59                 // Try to open a UDP socket
60                 $mainSocket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
61
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);
66                 } // END - if
67
68                 /*
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..
72                  */
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'));
77                         /*
78                         // Get socket error code for verification
79                         $socketError = socket_last_error($mainSocket);
80
81                         // Get error message
82                         $errorMessage = socket_strerror($socketError);
83
84                         // Shutdown this socket
85                         $this->shutdownSocket($mainSocket);
86
87                         // And throw again
88                         throw new InvalidSocketException(array($this, $mainSocket, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
89                         */
90                 } // END - if
91
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'));
97                         /*
98                         // Get socket error code for verification
99                         $socketError = socket_last_error($socket);
100
101                         // Get error message
102                         $errorMessage = socket_strerror($socketError);
103
104                         // Shutdown this socket
105                         $this->shutdownSocket($mainSocket);
106
107                         // And throw again
108                         throw new InvalidSocketException(array($this, $mainSocket, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
109                         */
110                 } // END - if
111
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'));
117                         /*
118                         // Get socket error code for verification
119                         $socketError = socket_last_error($mainSocket);
120
121                         // Get error message
122                         $errorMessage = socket_strerror($socketError);
123
124                         // Shutdown this socket
125                         $this->shutdownSocket($mainSocket);
126
127                         // And throw again
128                         throw new InvalidSocketException(array($this, $mainSocket, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
129                         */
130                 } // END - if
131
132                 // Remember the socket in our class
133                 $this->registerServerSocketResource($mainSocket);
134
135                 // Initialize the network package handler
136                 $handlerInstance = ObjectFactory::createObjectByConfiguredName('udp_raw_data_handler_class');
137
138                 // Set it in this class
139                 $this->setHandlerInstance($handlerInstance);
140
141                 // Output message
142                 self::createDebugInstance(__CLASS__)->debugOutput('UDP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: UDP listener now ready on IP ' . $this->getListenAddress() . ', port ' . $this->getListenPort() . ' for service.');
143         }
144
145         /**
146          * "Listens" for incoming network packages
147          *
148          * @return      void
149          * @todo        ~50% done
150          */
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);
154
155                 // Get last error
156                 $lastError = socket_last_error($this->getSocketResource());
157
158                 // Do we have an error at the line?
159                 if ($lastError == 11) {
160                         /*
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...
165                          */
166                         socket_clear_error($this->getSocketResource());
167
168                         // Skip further processing
169                         return;
170                 } elseif ($lastError > 0) {
171                         // Other error detected
172                         self::createDebugInstance(__CLASS__)->debugOutput('UDP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: Error detected: ' . socket_strerror($lastError));
173
174                         // Skip further processing
175                         return;
176                 } elseif ((empty($rawData)) || (trim($peer) == '')) {
177                         // Zero sized packages/peer names are usual in non-blocking mode
178                         return;
179                 } // END - if
180
181                 // Debug only
182                 self::createDebugInstance(__CLASS__)->debugOutput('UDP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: Handling UDP package with size ' . strlen($rawData) . ' from peer ' . $peer . ':' . $port);
183         }
184
185         /**
186          * Checks whether the listener would accept the given package data array
187          *
188          * @param       $packageData    Raw package data
189          * @return      $accepts                Whether this listener does accept
190          */
191         function ifListenerAcceptsPackageData (array $packageData) {
192                 $this->partialStub('This call should not happen. Please report it.');
193         }
194 }
195
196 // [EOF]
197 ?>