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") + ")");
198 for (String cipher
: getAnonCiphers()) {
199 if (!ciphers
.isEmpty()) {
204 tracer
.trace("Available SSL ciphers: " + ciphers
);
206 while (started
&& !exiting
) {
208 final Socket s
= ss
.accept();
209 new Thread(new Runnable() {
213 createConnectActionServer(s
).connect();
221 // Will be covered by @link{Server#stop(long)} for timeouts
222 while (counter
> 0) {
225 } catch (Exception e
) {
232 } catch (Exception e
) {
242 tracer
.trace(name
+ ": client terminated on port " + port
);
247 * Will stop the server, synchronously and without a timeout.
250 tracer
.trace(name
+ ": stopping server");
258 * the maximum timeout to wait for existing actions to complete,
259 * or 0 for "no timeout"
261 * wait for the server to be stopped before returning
262 * (synchronous) or not (asynchronous)
264 public void stop(final long timeout
, final boolean wait
) {
268 new Thread(new Runnable() {
278 * Stop the server (synchronous).
281 * the maximum timeout to wait for existing actions to complete,
282 * or 0 for "no timeout"
284 private void stop(long timeout
) {
285 tracer
.trace(name
+ ": server stopping on port " + port
);
286 synchronized (lock
) {
287 if (started
&& !exiting
) {
291 new ConnectActionClientObject(createSocket(null, port
, ssl
))
294 while (ss
!= null && timeout
> 0 && timeout
> time
) {
298 } catch (Exception e
) {
300 counter
= 0; // will stop the main thread
307 // return only when stopped
308 while (started
|| exiting
) {
311 } catch (InterruptedException e
) {
317 * Change the number of currently serviced actions.
320 * the number to increase or decrease
322 * @return the current number after this operation
324 private int count(int change
) {
325 synchronized (counterLock
) {
332 * This method will be called on errors.
334 * By default, it will only call the trace handler (so you may want to call
335 * super {@link Server#onError} if you override it).
340 protected void onError(Exception e
) {
345 * Create a {@link Socket}.
348 * the host to connect to
350 * the port to connect to
352 * TRUE for SSL mode (or FALSE for plain text mode)
354 * @return the {@link Socket}
356 * @throws IOException
357 * in case of I/O error
358 * @throws UnknownHostException
359 * if the host is not known
360 * @throws IllegalArgumentException
361 * if the port parameter is outside the specified range of valid
362 * port values, which is between 0 and 65535, inclusive
364 static Socket
createSocket(String host
, int port
, boolean ssl
)
368 s
= SSLSocketFactory
.getDefault().createSocket(host
, port
);
369 if (s
instanceof SSLSocket
) {
370 // Should always be the case
371 ((SSLSocket
) s
).setEnabledCipherSuites(ANON_CIPHERS
);
374 s
= new Socket(host
, port
);
381 * Create a {@link ServerSocket}.
384 * the port to accept connections on
386 * TRUE for SSL mode (or FALSE for plain text mode)
388 * @return the {@link ServerSocket}
390 * @throws IOException
391 * in case of I/O error
392 * @throws UnknownHostException
393 * if the IP address of the host could not be determined
394 * @throws IllegalArgumentException
395 * if the port parameter is outside the specified range of valid
396 * port values, which is between 0 and 65535, inclusive
398 static ServerSocket
createSocketServer(int port
, boolean ssl
)
402 ss
= SSLServerSocketFactory
.getDefault().createServerSocket(port
);
403 if (ss
instanceof SSLServerSocket
) {
404 // Should always be the case
405 ((SSLServerSocket
) ss
).setEnabledCipherSuites(ANON_CIPHERS
);
408 ss
= new ServerSocket(port
);
415 * Return all the supported ciphers that do not use authentication.
417 * @return the list of such supported ciphers
419 public static String
[] getAnonCiphers() {
420 List
<String
> anonCiphers
= new ArrayList
<String
>();
421 for (String cipher
: ((SSLSocketFactory
) SSLSocketFactory
.getDefault())
422 .getSupportedCipherSuites()) {
423 if (cipher
.contains("_anon_")) {
424 anonCiphers
.add(cipher
);
428 return anonCiphers
.toArray(new String
[] {});