KickJava   Java API By Example, From Geeks To Geeks.

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


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: JThreadServerSocket.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 JThreadServerSocket implements Runnable JavaDoc {
48
49   static final int INTERVAL = 100;
50   static final int ACCEPT_TIMEOUT = 2000;
51   
52   ServerSocket serverSok;
53   Thread JavaDoc serverThread;
54   ArrayList<JSocketEventListener> evtListener;
55   boolean bListening;
56   
57   
58
59   /**
60    * Constructor. Initializes all class
61    * data.
62    * @param nInitialPort Initial port to try
63    * begin to listen for connections.
64    * @param nEndPort End port to try begin to
65    * listen for connections.
66    */

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

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

120   private void fireOnAccept( Socket clientSok ) {
121
122     ArrayList<JSocketEventListener> clone;
123     
124     synchronized( this ) {
125       clone = ( ArrayList<JSocketEventListener> ) evtListener.clone();
126     }
127        
128     // Dispatch the onAccpet through the listener
129
if( clone.size() > 0 ) {
130       for( int nCount = 0; nCount < clone.size(); nCount++ )
131         ( ( JSocketEventListener ) evtListener ).onAccept( clientSok );
132     }
133   }
134  
135   /**
136    * Begin/End the ServerSocket listen
137    * in this class.
138    * @param bStart If true, the server will be
139    * listening, else stop listen;
140    */

141   public synchronized boolean listen( boolean bStart ) {
142     
143     if( bStart ) {
144       if( !serverThread.isAlive() ) {
145         bListening = true;
146         serverThread.start();
147       }
148     }
149     else {
150       
151       /*
152       try {
153         serverSok.close();
154       } catch( java.io.IOException e ) {
155         System.err.println( "JThreadServerSocket.listen( false ) - " + e );
156       }*/

157
158       if( bListening ) {
159         serverThread.interrupt();
160         bListening = false;
161       
162         try {
163           close();
164           wait();
165           System.err.println( "JThreadServerSocket.listen( false ) performed" );
166         } catch( java.lang.InterruptedException JavaDoc ie ) {
167           System.err.println( "JThreadServerSocket.listen( false ) - " + ie );
168         } catch( java.lang.IllegalMonitorStateException JavaDoc me ) {
169           System.err.println( "JThreadServerSocket.listen( false ) - " + me );
170         }
171       }
172     }
173     
174     return true;
175   }
176    
177   /**
178    * Close the server connection.
179    */

180   public void close() {
181     
182     try {
183       serverSok.close();
184     } catch( java.io.IOException JavaDoc e ) {
185       System.err.println( "JThreadServerSocket.close() - " + e );
186     }
187   }
188
189   /**
190    * Attach a JSocketEventListener to object
191    * assigned by this class.
192    * The listener attached will response all
193    * network events managed by this
194    * JThreadSocketServerSocket.
195    * @param evt The Listener object that will
196    * response all network events of this
197    * class;
198    */

199   public synchronized void addSocketEventListener( org.planetamessenger.net.JSocketEventListener evt ) {
200
201     evtListener.add( evt );
202   }
203   
204   
205   /**
206    * Remove the JSocketEventListener to object
207    * passed by parameter.
208    * @param evt The object listener to remove;
209    */

210   public synchronized void removeSocketEventListener( org.planetamessenger.net.JSocketEventListener evt ) {
211     
212     evtListener.remove( evt );
213   }
214
215   /**
216    * Returns the local port assigned to this
217    * class object.
218    */

219   public int getLocalPort() {
220     
221     return serverSok.getLocalPort();
222   }
223
224   /**
225    * Returns the InetAddress of this
226    * ServerSocket.
227    */

228   public InetAddress getInetAddress() {
229     
230     return serverSok.getInetAddress();
231   }
232
233   /**
234    * Implements the entry-point of
235    * thread socket manager.
236    */

237   public void run() {
238     
239     while( true ) {
240     
241       try {
242         
243         // Check exit notification
244
if( !bListening )
245           break;
246       
247         Thread.sleep( INTERVAL );
248       } catch( InterruptedException JavaDoc e ) {
249         System.err.println( "JThreadServerSocket.run() - " + e );
250         break;
251       }
252         
253       try {
254         java.net.Socket JavaDoc clientSok = serverSok.accept();
255
256         fireOnAccept( clientSok );
257         
258       } catch( java.io.IOException JavaDoc e ) {
259         //System.err.println( "JThreadServerSocket.run() - " + e );
260
}
261     }
262     
263     // Notify the main thread to exit
264
notifyMainThread();
265   }
266 }
267
268 // JThreadServerSocket class
269
Popular Tags