1 package be
.nikiroo
.utils
.serial
;
3 import java
.io
.IOException
;
4 import java
.net
.ServerSocket
;
5 import java
.net
.Socket
;
6 import java
.util
.ArrayList
;
9 import javax
.net
.ssl
.SSLServerSocket
;
10 import javax
.net
.ssl
.SSLServerSocketFactory
;
11 import javax
.net
.ssl
.SSLSocket
;
12 import javax
.net
.ssl
.SSLSocketFactory
;
14 import be
.nikiroo
.utils
.TraceHandler
;
15 import be
.nikiroo
.utils
.Version
;
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 public 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 public Server(@SuppressWarnings("unused") Version notUsed
, int port
,
45 boolean ssl
) throws IOException
{
50 * Create a new server that will start listening on the network when
51 * {@link Server#start()} is called.
54 * the port to listen on, or 0 to assign any unallocated port
55 * found (which can later on be queried via
56 * {@link Server#getPort()}
58 * use a SSL connection (or not)
61 * in case of I/O error
63 public Server(int port
, boolean ssl
) throws IOException
{
64 this((String
) null, port
, ssl
);
68 * Create a new server that will start listening on the network when
69 * {@link Server#start()} is called.
72 * the server name (only used for debug info and traces)
74 * the port to listen on
76 * use a SSL connection (or not)
79 * in case of I/O error
81 public Server(String name
, int port
, boolean ssl
) throws IOException
{
85 this.ss
= createSocketServer(port
, ssl
);
88 this.port
= this.ss
.getLocalPort();
93 * The traces handler for this {@link Server}.
95 * @return the traces handler
97 public TraceHandler
getTraceHandler() {
102 * The traces handler for this {@link Server}.
105 * the new traces handler
107 public void setTraceHandler(TraceHandler tracer
) {
108 if (tracer
== null) {
109 tracer
= new TraceHandler(false, false, false);
112 this.tracer
= tracer
;
116 * Return the assigned port.
118 * @return the assigned port
120 public int getPort() {
125 * Start the server (listen on the network for new connections).
127 * Can only be called once.
129 * This call is synchronous.
131 public void start() {
136 * Start the server (listen on the network for new connections).
138 * Can only be called once.
141 * TRUE for synchronous, FALSE for asynchronous
143 public void start(boolean wait
) {
145 synchronized (lock
) {
146 if (!started
&& ss
!= null) {
150 new Thread(this).start();
156 tracer
.trace(name
+ ": server started on port " + port
);
160 } else if (ss
== null) {
161 tracer
.error(name
+ ": cannot start server on port " + port
162 + ", it has already been used");
164 tracer
.error(name
+ ": cannot start server on port " + port
165 + ", it is already started");
170 * Will stop the server, synchronously and without a timeout.
173 tracer
.trace(name
+ ": stopping server");
181 * the maximum timeout to wait for existing actions to complete,
182 * or 0 for "no timeout"
184 * wait for the server to be stopped before returning
185 * (synchronous) or not (asynchronous)
187 public void stop(final long timeout
, final boolean wait
) {
191 new Thread(new Runnable() {
201 * Stop the server (synchronous).
204 * the maximum timeout to wait for existing actions to complete,
205 * or 0 for "no timeout"
207 private void stop(long timeout
) {
208 synchronized (lock
) {
209 if (started
&& !exiting
) {
213 new ConnectActionClient(createSocket(null, port
, ssl
))
216 while (ss
!= null && timeout
> 0 && timeout
> time
) {
220 } catch (Exception e
) {
222 counter
= 0; // will stop the main thread
228 // only return when stopped
229 while (started
|| exiting
) {
232 } catch (InterruptedException e
) {
241 while (started
&& !exiting
) {
243 Socket s
= ss
.accept();
244 new ConnectActionServer(s
) {
246 public void action(Version clientVersion
) throws Exception
{
248 for (Object data
= rec(); true; data
= rec()) {
251 rep
= onRequest(this, clientVersion
, data
);
252 } catch (Exception e
) {
257 } catch (NullPointerException e
) {
258 // Client has no data any more, we quit
259 tracer
.trace("Client has data no more, stopping connection");
264 public void connect() {
274 // Will be covered by @link{Server#stop(long)} for timeouts
275 while (counter
> 0) {
278 } catch (Exception e
) {
285 } catch (Exception e
) {
298 * This is the method that is called on each client request.
300 * You are expected to react to it and return an answer (which can be NULL).
304 * @param clientVersion
307 * the data sent by the client (which can be NULL)
309 * @return the answer to return to the client (which can be NULL)
312 * in case of an exception, the error will only be logged
314 abstract protected Object
onRequest(ConnectActionServer action
,
315 Version clientVersion
, Object data
) throws Exception
;
318 * This method will be called on errors.
320 * By default, it will only call the trace handler (so you may want to call
321 * super {@link Server#onError} if you override it).
326 protected void onError(Exception e
) {
331 * Change the number of currently serviced actions.
334 * the number to increase or decrease
336 * @return the current number after this operation
338 private int count(int change
) {
339 synchronized (counterLock
) {
346 * Create a {@link Socket}.
349 * the host to connect to
351 * the port to connect to
353 * TRUE for SSL mode (or FALSE for plain text mode)
355 * @return the {@link Socket}
357 * @throws IOException
358 * in case of I/O error
360 static Socket
createSocket(String host
, int port
, boolean ssl
)
364 s
= SSLSocketFactory
.getDefault().createSocket(host
, port
);
365 ((SSLSocket
) s
).setEnabledCipherSuites(ANON_CIPHERS
);
367 s
= new Socket(host
, port
);
374 * Create a {@link ServerSocket}.
377 * the port to accept connections on
379 * TRUE for SSL mode (or FALSE for plain text mode)
381 * @return the {@link ServerSocket}
383 * @throws IOException
384 * in case of I/O error
386 static ServerSocket
createSocketServer(int port
, boolean ssl
)
390 ss
= SSLServerSocketFactory
.getDefault().createServerSocket(port
);
391 ((SSLServerSocket
) ss
).setEnabledCipherSuites(ANON_CIPHERS
);
393 ss
= new ServerSocket(port
);
400 * Return all the supported ciphers that do not use authentication.
402 * @return the list of such supported ciphers
404 private static String
[] getAnonCiphers() {
405 List
<String
> anonCiphers
= new ArrayList
<String
>();
406 for (String cipher
: ((SSLSocketFactory
) SSLSocketFactory
.getDefault())
407 .getSupportedCipherSuites()) {
408 if (cipher
.contains("_anon_")) {
409 anonCiphers
.add(cipher
);
413 return anonCiphers
.toArray(new String
[] {});