]> git.mxchange.org Git - hub.git/blob - application/hub/main/listener/udp/class_UdpListener.php
Updated 'core'.
[hub.git] / application / hub / main / 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          * @param       $nodeInstance           A NodeHelper instance
42          * @return      $listenerInstance       An instance a prepared listener class
43          */
44         public static final function createUdpListener (NodeHelper $nodeInstance) {
45                 // Get new instance
46                 $listenerInstance = new UdpListener();
47
48                 // Return the prepared instance
49                 return $listenerInstance;
50         }
51
52         /**
53          * Initializes the listener by setting up the required socket server
54          *
55          * @return      void
56          * @throws      InvalidSocketException  Thrown if the socket is invalid or an
57          *                                                                      error was detected.
58          */
59         public function initListener () {
60                 // Try to open a UDP socket
61                 $mainSocket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
62
63                 // Is the socket a valid resource or do we have any error?
64                 if (!is_resource($mainSocket)) {
65                         // Then throw an InvalidSocketException
66                         throw new InvalidSocketException(array($this, $mainSocket), BaseListener::EXCEPTION_INVALID_SOCKET);
67                 } // END - if
68
69                 /*
70                  * "Bind" the socket to the given address, on given port so this means
71                  * that all connections on this port are now our resposibility to
72                  * send/recv data, disconnect, etc..
73                  */
74                 self::createDebugInstance(__CLASS__)->debugOutput('UDP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: Binding to address ' . $this->getListenAddress() . ':' . $this->getListenPort());
75                 if (!socket_bind($mainSocket, $this->getListenAddress(), $this->getListenPort())) {
76                         // Handle the socket error with a faked recipientData array
77                         $this->handleSocketError(__METHOD__, __LINE__, $mainSocket, array('0.0.0.0', '0'));
78                         /*
79                         // Get socket error code for verification
80                         $socketError = socket_last_error($mainSocket);
81
82                         // Get error message
83                         $errorMessage = socket_strerror($socketError);
84
85                         // Shutdown this socket
86                         $this->shutdownSocket($mainSocket);
87
88                         // And throw again
89                         throw new InvalidSocketException(array($this, $mainSocket, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
90                         */
91                 } // END - if
92
93                 // Now, we want non-blocking mode
94                 self::createDebugInstance(__CLASS__)->debugOutput('UDP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: Setting non-blocking mode.');
95                 if (!socket_set_nonblock($mainSocket)) {
96                         // Handle the socket error with a faked recipientData array
97                         $this->handleSocketError(__METHOD__, __LINE__, $mainSocket, array('0.0.0.0', '0'));
98                         /*
99                         // Get socket error code for verification
100                         $socketError = socket_last_error($socket);
101
102                         // Get error message
103                         $errorMessage = socket_strerror($socketError);
104
105                         // Shutdown this socket
106                         $this->shutdownSocket($mainSocket);
107
108                         // And throw again
109                         throw new InvalidSocketException(array($this, $mainSocket, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
110                         */
111                 } // END - if
112
113                 // Set the option to reuse the port
114                 self::createDebugInstance(__CLASS__)->debugOutput('UDP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: Setting re-use address option.');
115                 if (!socket_set_option($mainSocket, SOL_SOCKET, SO_REUSEADDR, 1)) {
116                         // Handle the socket error with a faked recipientData array
117                         $this->handleSocketError(__METHOD__, __LINE__, $mainSocket, array('0.0.0.0', '0'));
118                         /*
119                         // Get socket error code for verification
120                         $socketError = socket_last_error($mainSocket);
121
122                         // Get error message
123                         $errorMessage = socket_strerror($socketError);
124
125                         // Shutdown this socket
126                         $this->shutdownSocket($mainSocket);
127
128                         // And throw again
129                         throw new InvalidSocketException(array($this, $mainSocket, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
130                         */
131                 } // END - if
132
133                 // Remember the socket in our class
134                 $this->registerServerSocketResource($mainSocket);
135
136                 // Initialize the network package handler
137                 $handlerInstance = ObjectFactory::createObjectByConfiguredName('udp_raw_data_handler_class');
138
139                 // Set it in this class
140                 $this->setHandlerInstance($handlerInstance);
141
142                 // Output message
143                 self::createDebugInstance(__CLASS__)->debugOutput('UDP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: UDP listener now ready on IP ' . $this->getListenAddress() . ', port ' . $this->getListenPort() . ' for service.');
144         }
145
146         /**
147          * "Listens" for incoming network packages
148          *
149          * @return      void
150          * @todo        ~50% done
151          */
152         public function doListen() {
153                 // Read a package and determine the peer
154                 $amount = @socket_recvfrom($this->getSocketResource(), $rawData, $this->getConfigInstance()->getConfigEntry('udp_buffer_length'), MSG_DONTWAIT, $peer, $port);
155
156                 // Get last error
157                 $lastError = socket_last_error($this->getSocketResource());
158
159                 // Do we have an error at the line?
160                 if ($lastError == 11) {
161                         /*
162                          * This (resource temporary unavailable) can be safely ignored on
163                          * "listening" UDP ports. If we don't clear the error here, our UDP
164                          * "listener" won't read any packages except if the UDP sender
165                          * starts the transmission before this "listener" came up...
166                          */
167                         socket_clear_error($this->getSocketResource());
168
169                         // Skip further processing
170                         return;
171                 } elseif ($lastError > 0) {
172                         // Other error detected
173                         self::createDebugInstance(__CLASS__)->debugOutput('UDP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: Error detected: ' . socket_strerror($lastError));
174
175                         // Skip further processing
176                         return;
177                 } elseif ((empty($rawData)) || (trim($peer) == '')) {
178                         // Zero sized packages/peer names are usual in non-blocking mode
179                         return;
180                 } // END - if
181
182                 // Debug only
183                 self::createDebugInstance(__CLASS__)->debugOutput('UDP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: Handling UDP package with size ' . strlen($rawData) . ' from peer ' . $peer . ':' . $port);
184         }
185
186         /**
187          * Checks whether the listener would accept the given package data array
188          *
189          * @param       $packageData    Raw package data
190          * @return      $accepts                Whether this listener does accept
191          */
192         function ifListenerAcceptsPackageData (array $packageData) {
193                 $this->partialStub('This call should not happen. Please report it.');
194         }
195 }
196
197 // [EOF]
198 ?>