]> git.mxchange.org Git - hub.git/blob - application/hub/main/listener/udp/class_UdpListener.php
'public static final' is the right thing, some variables renamed to make clear what...
[hub.git] / application / hub / main / listener / udp / class_UdpListener.php
1 <?php
2 /**
3  * An UDP connection listener
4  *
5  * @author              Roland Haeder <webmaster@ship-simu.org>
6  * @version             0.0.0
7  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009, 2010 Hub Developer Team
8  * @license             GNU GPL 3.0 or any newer version
9  * @link                http://www.ship-simu.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
35         /**
36          * Creates an instance of this class
37          *
38          * @param       $nodeInstance           A NodeHelper instance
39          * @return      $listenerInstance       An instance a prepared listener class
40          */
41         public static final function createUdpListener (NodeHelper $nodeInstance) {
42                 // Get new instance
43                 $listenerInstance = new UdpListener();
44
45                 // Set the application instance
46                 $listenerInstance->setNodeInstance($nodeInstance);
47
48                 // Set the protocol to UDP
49                 $listenerInstance->setProtocol('udp');
50
51                 // Return the prepared instance
52                 return $listenerInstance;
53         }
54
55         /**
56          * Initializes the listener by setting up the required socket server
57          *
58          * @return      void
59          * @throws      InvalidSocketException  Thrown if the socket is invalid or an
60          *                                                                      error was detected.
61          */
62         public function initListener () {
63                 // Try to open a UDP socket
64                 $mainSocket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
65
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, gettype($mainSocket), $errno, $errstr), BaseListener::EXCEPTION_INVALID_SOCKET);
70                 } // END - if
71
72                 // Set the option to reuse the port
73                 $this->debugOutput('LISTENER: Setting re-use address option.');
74                 if (!socket_set_option($mainSocket, SOL_SOCKET, SO_REUSEADDR, 1)) {
75                         // Get socket error code for verification
76                         $socketError = socket_last_error($mainSocket);
77
78                         // Get error message
79                         $errorMessage = socket_strerror($socketError);
80
81                         // Shutdown this socket
82                         $this->shutdownSocket($mainSocket);
83
84                         // And throw again
85                         throw new InvalidSocketException(array($this, gettype($mainSocket), $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
86                 } // END - if
87
88                 // "Bind" the socket to the given address, on given port so this means
89                 // that all connections on this port are now our resposibility to
90                 // send/recv data, disconnect, etc..
91                 $this->debugOutput('LISTENER: Binding to address ' . $this->getListenAddress() . ':' . $this->getListenPort());
92                 if (!socket_bind($mainSocket, $this->getListenAddress(), $this->getListenPort())) {
93                         // Get socket error code for verification
94                         $socketError = socket_last_error($mainSocket);
95
96                         // Get error message
97                         $errorMessage = socket_strerror($socketError);
98
99                         // Shutdown this socket
100                         $this->shutdownSocket($mainSocket);
101
102                         // And throw again
103                         throw new InvalidSocketException(array($this, gettype($mainSocket), $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
104                 } // END - if
105
106                 // Now, we want non-blocking mode
107                 $this->debugOutput('LISTENER: Setting non-blocking mode.');
108                 if (!socket_set_nonblock($mainSocket)) {
109                         // Get socket error code for verification
110                         $socketError = socket_last_error($socket);
111
112                         // Get error message
113                         $errorMessage = socket_strerror($socketError);
114
115                         // Shutdown this socket
116                         $this->shutdownSocket($mainSocket);
117
118                         // And throw again
119                         throw new InvalidSocketException(array($this, gettype($mainSocket), $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
120                 } // END - if
121
122                 // Remember the socket in our class
123                 $this->registerServerSocketResource($mainSocket);
124
125                 // Output message
126                 $this->debugOutput('LISTENER: UDP listener now ready on IP ' . $this->getListenAddress() . ', port ' . $this->getListenPort() . ' for service.');
127         }
128
129         /**
130          * "Listens" for incoming network packages
131          *
132          * @return      void
133          * @todo        ~50% done
134          */
135         public function doListen() {
136                 // Read a package and determine the peer
137                 $amount = @socket_recvfrom($this->getSocketResource(), $pkt, 1500, 0, $peer, $port);
138
139                 // Get last error
140                 $lastError = socket_last_error($this->getSocketResource());
141
142                 // Do we have an error at the line?
143                 if ($lastError == 11) {
144                         /*
145                          * This (resource temporary unavailable) can be safely ignored on
146                          * "listening" UDP ports. If we don't clear the error here, our UDP
147                          * "listener" won't read any packages except if the UDP sender
148                          * starts the transmission before this "listener came up...
149                          */
150                         socket_clear_error($this->getSocketResource());
151
152                         // Skip further processing
153                         return;
154                 } elseif ($lastError > 0) {
155                         // Other error detected
156                         $this->debugOutput('LISTENER: Error detected: ' . socket_strerror($lastError));
157
158                         // Skip further processing
159                         return;
160                 } elseif ((empty($pkt)) || (trim($peer) == '')) {
161                         // Zero sized packages/peer names are usual in non-blocking mode
162                         return;
163                 } // END - if
164
165                 // Debug only
166                 $this->debugOutput('LISTENER: Handling UDP package with size ' . strlen($pkt) . ' from peer ' . $peer . ':' . $port);
167         }
168
169         /**
170          * Checks wether the listener would accept the given package data array
171          *
172          * @param       $packageData    Raw package data
173          * @return      $accepts                Wether this listener does accept
174          */
175         function ifListenerAcceptsPackageData (array $packageData) {
176                 $this->partialStub('This call should not happen. Please report it.');
177         }
178 }
179
180 // [EOF]
181 ?>