afceaf95323ec349825372c858b65fc95f185761
1 package be
.nikiroo
.utils
.serial
.server
;
3 import java
.io
.IOException
;
4 import java
.net
.ServerSocket
;
5 import java
.net
.Socket
;
6 import java
.net
.UnknownHostException
;
7 import java
.util
.ArrayList
;
10 import javax
.net
.ssl
.SSLServerSocket
;
11 import javax
.net
.ssl
.SSLServerSocketFactory
;
12 import javax
.net
.ssl
.SSLSocket
;
13 import javax
.net
.ssl
.SSLSocketFactory
;
15 import be
.nikiroo
.utils
.TraceHandler
;
18 * This class implements a simple server that can listen for connections and
19 * send/receive objects.
21 * Note: this {@link Server} has to be discarded after use (cannot be started
26 abstract class Server
implements Runnable
{
27 static private final String
[] ANON_CIPHERS
= getAnonCiphers();
29 private final String name
;
30 private final boolean ssl
;
31 private final Object lock
= new Object();
32 private final Object counterLock
= new Object();
34 private ServerSocket ss
;
37 private boolean started
;
38 private boolean exiting
= false;
41 private TraceHandler tracer
= new TraceHandler();
44 * Create a new {@link ConnectActionServer} to handle a request.
47 * the socket to service
51 abstract ConnectActionServer
createConnectActionServer(Socket s
);
54 * Create a new server that will start listening on the network when
55 * {@link Server#start()} is called.
58 * the port to listen on, or 0 to assign any unallocated port
59 * found (which can later on be queried via
60 * {@link Server#getPort()}
62 * use a SSL connection (or not)
65 * in case of I/O error
66 * @throws UnknownHostException
67 * if the IP address of the host could not be determined
68 * @throws IllegalArgumentException
69 * if the port parameter is outside the specified range of valid
70 * port values, which is between 0 and 65535, inclusive
72 public Server(int port
, boolean ssl
) throws IOException
{
73 this((String
) null, port
, ssl
);
77 * Create a new server that will start listening on the network when
78 * {@link Server#start()} is called.
81 * the server name (only used for debug info and traces)
83 * the port to listen on
85 * use a SSL connection (or not)
88 * in case of I/O error
89 * @throws UnknownHostException
90 * if the IP address of the host could not be determined
91 * @throws IllegalArgumentException
92 * if the port parameter is outside the specified range of valid
93 * port values, which is between 0 and 65535, inclusive
95 public Server(String name
, int port
, boolean ssl
) throws IOException
{
99 this.ss
= createSocketServer(port
, ssl
);
101 if (this.port
== 0) {
102 this.port
= this.ss
.getLocalPort();
107 * The traces handler for this {@link Server}.
109 * @return the traces handler
111 public TraceHandler
getTraceHandler() {
116 * The traces handler for this {@link Server}.
119 * the new traces handler
121 public void setTraceHandler(TraceHandler tracer
) {
122 if (tracer
== null) {
123 tracer
= new TraceHandler(false, false, false);
126 this.tracer
= tracer
;
130 * The name of this {@link Server} if any.
132 * Used for traces and debug purposes only.
134 * @return the name or NULL
136 public String
getName() {
141 * Return the assigned port.
143 * @return the assigned port
145 public int getPort() {
150 * Start the server (listen on the network for new connections).
152 * Can only be called once.
154 * This call is asynchronous, and will just start a new {@link Thread} on
155 * itself (see {@link Server#run()}).
157 public void start() {
158 new Thread(this).start();
162 * Start the server (listen on the network for new connections).
164 * Can only be called once.
166 * You may call it via {@link Server#start()} for an asynchronous call, too.
170 ServerSocket ss
= null;
171 boolean alreadyStarted
= false;
172 synchronized (lock
) {
174 if (!started
&& ss
!= null) {
177 alreadyStarted
= started
;
181 if (alreadyStarted
) {
182 tracer
.error(name
+ ": cannot start server on port " + port
183 + ", it is already started");
188 tracer
.error(name
+ ": cannot start server on port " + port
189 + ", it has already been used");
194 tracer
.trace(name
+ ": server starting on port " + port
+ " ("
195 + (ssl ?
"SSL" : "plain text") + ")");
197 while (started
&& !exiting
) {
199 final Socket s
= ss
.accept();
200 new Thread(new Runnable() {
204 createConnectActionServer(s
).connect();
212 // Will be covered by @link{Server#stop(long)} for timeouts
213 while (counter
> 0) {
216 } catch (Exception e
) {
223 } catch (Exception e
) {
233 tracer
.trace(name
+ ": client terminated on port " + port
);
238 * Will stop the server, synchronously and without a timeout.
241 tracer
.trace(name
+ ": stopping server");
249 * the maximum timeout to wait for existing actions to complete,
250 * or 0 for "no timeout"
252 * wait for the server to be stopped before returning
253 * (synchronous) or not (asynchronous)
255 public void stop(final long timeout
, final boolean wait
) {
259 new Thread(new Runnable() {
269 * Stop the server (synchronous).
272 * the maximum timeout to wait for existing actions to complete,
273 * or 0 for "no timeout"
275 private void stop(long timeout
) {
276 tracer
.trace(name
+ ": server stopping on port " + port
);
277 synchronized (lock
) {
278 if (started
&& !exiting
) {
282 new ConnectActionClientObject(createSocket(null, port
, ssl
))
285 while (ss
!= null && timeout
> 0 && timeout
> time
) {
289 } catch (Exception e
) {
291 counter
= 0; // will stop the main thread
298 // return only when stopped
299 while (started
|| exiting
) {
302 } catch (InterruptedException e
) {
308 * Change the number of currently serviced actions.
311 * the number to increase or decrease
313 * @return the current number after this operation
315 private int count(int change
) {
316 synchronized (counterLock
) {
323 * This method will be called on errors.
325 * By default, it will only call the trace handler (so you may want to call
326 * super {@link Server#onError} if you override it).
331 protected void onError(Exception e
) {
336 * Create a {@link Socket}.
339 * the host to connect to
341 * the port to connect to
343 * TRUE for SSL mode (or FALSE for plain text mode)
345 * @return the {@link Socket}
347 * @throws IOException
348 * in case of I/O error
349 * @throws UnknownHostException
350 * if the host is not known
351 * @throws IllegalArgumentException
352 * if the port parameter is outside the specified range of valid
353 * port values, which is between 0 and 65535, inclusive
355 static Socket
createSocket(String host
, int port
, boolean ssl
)
359 s
= SSLSocketFactory
.getDefault().createSocket(host
, port
);
360 if (s
instanceof SSLSocket
) {
361 // Should always be the case
362 ((SSLSocket
) s
).setEnabledCipherSuites(ANON_CIPHERS
);
365 s
= new Socket(host
, port
);
372 * Create a {@link ServerSocket}.
375 * the port to accept connections on
377 * TRUE for SSL mode (or FALSE for plain text mode)
379 * @return the {@link ServerSocket}
381 * @throws IOException
382 * in case of I/O error
383 * @throws UnknownHostException
384 * if the IP address of the host could not be determined
385 * @throws IllegalArgumentException
386 * if the port parameter is outside the specified range of valid
387 * port values, which is between 0 and 65535, inclusive
389 static ServerSocket
createSocketServer(int port
, boolean ssl
)
393 ss
= SSLServerSocketFactory
.getDefault().createServerSocket(port
);
394 if (ss
instanceof SSLServerSocket
) {
395 // Should always be the case
396 ((SSLServerSocket
) ss
).setEnabledCipherSuites(ANON_CIPHERS
);
399 ss
= new ServerSocket(port
);
406 * Return all the supported ciphers that do not use authentication.
408 * @return the list of such supported ciphers
410 private static String
[] getAnonCiphers() {
411 List
<String
> anonCiphers
= new ArrayList
<String
>();
412 for (String cipher
: ((SSLSocketFactory
) SSLSocketFactory
.getDefault())
413 .getSupportedCipherSuites()) {
414 if (cipher
.contains("_anon_")) {
415 anonCiphers
.add(cipher
);
419 return anonCiphers
.toArray(new String
[] {});