KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > planetamessenger > net > JThreadServerUDP


1 /*
2     =========================================================================
3     Package net - Implements Network classes.
4
5     This module is developed and maintained by PlanetaMessenger.org.
6     Specs, New and updated versions can be found in
7     http://www.planetamessenger.org
8     If you want contact the Team please send a email to Project Manager
9     Leidson Campos Alves Ferreira at leidson@planetamessenger.org
10
11     Copyright (C) since 2001 by PlanetaMessenger.org
12     
13     This library is free software; you can redistribute it and/or
14     modify it under the terms of the GNU Lesser General Public
15     License as published by the Free Software Foundation; either
16     version 2.1 of the License, or (at your option) any later version.
17
18     This library is distributed in the hope that it will be useful,
19     but WITHOUT ANY WARRANTY; without even the implied warranty of
20     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21     Lesser General Public License for more details.
22
23     You should have received a copy of the GNU Lesser General Public
24     License along with this library; if not, write to the Free Software
25     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26
27     =========================================================================
28 */

29 /**
30  *
31  * $Id: JThreadServerUDP.java,v 1.10 2007/01/28 17:39:21 popolony2k Exp $
32  * $Author: popolony2k $
33  * $Name: $
34  * $Revision: 1.10 $
35  * $State: Exp $
36  *
37  */

38
39 package org.planetamessenger.net;
40
41 import java.net.*;
42 import java.util.*;
43 import java.io.IOException JavaDoc;
44
45
46
47 public class JThreadServerUDP implements Runnable JavaDoc {
48   
49   static final int INTERVAL = 100;
50   static final int RECEIVE_TIMEOUT = 2000;
51   static final int DEF_DATAGRAM_BUFFER_SIZE = 8192;
52   
53   DatagramSocket serverUDP;
54   Thread JavaDoc serverThread;
55   ArrayList<JDatagramEventListener> evtListener;
56   int nPacketSize;
57   boolean bListening;
58   
59   
60   
61   /**
62    * Constructor. Initializes all class
63    * data.
64    * @param nInitialPort Initial port to try
65    * begin to listen for connections.
66    * @param nEndPort End port to try begin to
67    * listen for connections.
68    */

69   public JThreadServerUDP( int nInitialPort, int nEndPort ) throws java.io.IOException JavaDoc {
70     
71     boolean bSocketOk = true;
72     java.io.IOException JavaDoc e;
73
74   
75     bListening = false;
76     evtListener = new ArrayList<JDatagramEventListener>();
77     nPacketSize = DEF_DATAGRAM_BUFFER_SIZE;
78     
79     for( int nPort = nInitialPort; nPort <= nEndPort; nPort++ ) {
80       try {
81         serverUDP = new DatagramSocket( nPort );
82         bSocketOk = true;
83         break;
84       } catch( IOException JavaDoc ex ) {
85         bSocketOk = false;
86       }
87     }
88
89     if( !bSocketOk ) {
90       e = new java.io.IOException JavaDoc( "org.planetamessenger.net exception - Cannot open a JThreadServerUDP" );
91       throw e;
92     }
93     else
94       try {
95         serverUDP.setSoTimeout( RECEIVE_TIMEOUT );
96         serverThread = new Thread JavaDoc( this );
97       } catch( java.net.SocketException JavaDoc ex ) {
98         e = new java.io.IOException JavaDoc( "org.planetamessenger.net exception - Cannot open a JThreadServerUDP" );
99         throw e;
100       }
101   }
102
103   /**
104    * Notify the the main thread to unlock
105    * the waiting object synchro.
106    */

107   private synchronized void notifyMainThread() {
108     
109     try {
110       System.err.println( "JThreadServerUDP.notifyMainThread() - Normal Thread exit." );
111       notifyAll();
112     } catch( java.lang.IllegalMonitorStateException JavaDoc me ) {
113       System.err.println( "JThreadServerUDP.notifyMainThread() - " + me );
114     }
115   }
116   
117   /**
118    * Fire the onReceive event.
119    * @param clientPak The client datagram packet opened
120    * with connection stablished.
121    */

122   private void fireOnReceive( java.net.DatagramPacket JavaDoc clientPak ) {
123
124     ArrayList<JDatagramEventListener> clone;
125     
126     synchronized( this ) {
127       clone = ( ArrayList<JDatagramEventListener> ) evtListener.clone();
128     }
129        
130     // Dispatch the onAccpet through the listener
131
if( clone.size() > 0 ) {
132       for( int nCount = 0; nCount < clone.size(); nCount++ )
133         ( ( JDatagramEventListener ) evtListener ).onReceive( clientPak );
134     }
135   }
136
137   /**
138    * Attaches a JSocketEventListener to object
139    * assigned by this class.
140    * The listener attached will response all
141    * network events managed by this
142    * JThreadSocketServerUDP.
143    * @param evt The Listener object that will
144    * response all network events of this class;
145    */

146   public synchronized void addDatagramEventListener( org.planetamessenger.net.JDatagramEventListener evt ) {
147     
148     evtListener.add( evt );
149   }
150   
151   /**
152    * Remove the JDatagramEventListener to object
153    * passed by parameter.
154    * @param evt The object listener to remove;
155    */

156   public synchronized void removeDatagramEventListener( org.planetamessenger.net.JDatagramEventListener evt ) {
157     
158     evtListener.remove( evt );
159   }
160   
161   /**
162    * Sets the DatagramPacket size. This function
163    * will fail if the UDP Server is in listen
164    * mode.
165    * @param nPacketSize The new packetnsize;
166    */

167   public boolean setPacketSize( int nPacketSize ) {
168     
169     if( !serverThread.isAlive() )
170       this.nPacketSize = nPacketSize;
171     else
172       return false;
173     
174     return true;
175   }
176   
177   /**
178    * Returns the Packet Size of this
179    * UDP server.
180    */

181   int getPacketSize() {
182
183     return nPacketSize;
184   }
185
186   /**
187    * Begins/Ends the ServerSocket listen
188    * in this class.
189    * @param bStart If true, the server will be
190    * listening, else stop listen;
191    */

192   public synchronized boolean listen( boolean bStart ) {
193     
194     if( bStart ) {
195       if( !serverThread.isAlive() ) {
196         bListening = true;
197         serverThread.start();
198       }
199     }
200     else {
201       
202       if( bListening ) {
203         serverThread.interrupt();
204         bListening = false;
205       
206         try {
207           close();
208           wait();
209           System.err.println( "JThreadServerUDP.listen( false ) performed" );
210         } catch( java.lang.InterruptedException JavaDoc ie ) {
211           System.err.println( "JThreadServerUDP.listen( false ) - " + ie );
212         } catch( java.lang.IllegalMonitorStateException JavaDoc me ) {
213           System.err.println( "JThreadServerUDP.listen( false ) - " + me );
214         }
215       }
216     }
217     
218     return true;
219   }
220
221   /**
222    * Close the server UDP connection.
223    */

224   public void close() {
225     
226     serverUDP.close();
227   }
228
229   /**
230    * Returns the local port assigned to this
231    * class object.
232    */

233   public int getLocalPort() {
234
235     return serverUDP.getLocalPort();
236   }
237
238   /**
239    * Implements the entry-point of
240    * thread socket manager.
241    */

242   public void run() {
243    
244     byte[] packet = new byte[nPacketSize];
245     
246     
247     while( true ) {
248     
249       try {
250         
251         // Check exit notification
252
if( !bListening )
253           break;
254       
255         Thread.sleep( INTERVAL );
256         
257       } catch( InterruptedException JavaDoc e ) {
258         System.err.println( "JThreadServerUDP.run() - " + e );
259         break;
260       }
261         
262       try {
263         java.net.DatagramPacket JavaDoc clientPak = new DatagramPacket( packet, packet.length );
264
265         serverUDP.receive( clientPak );
266         
267         fireOnReceive( clientPak );
268         
269       } catch( java.io.IOException JavaDoc e ) {
270         //System.err.println( "JThreadServerUDP.run() - " + e );
271
}
272     }
273     
274     // Notify the main thread to exit
275
notifyMainThread();
276   }
277 }
278
279 // JThreadServerUDP class
Popular Tags