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 public int getPort() {
123 * Start the server (listen on the network for new connections).
125 * Can only be called once.
127 public void start() {
129 synchronized (lock
) {
130 if (!started
&& ss
!= null) {
132 new Thread(this).start();
138 tracer
.trace(name
+ ": server started on port " + port
);
139 } else if (ss
== null) {
140 tracer
.error(name
+ ": cannot start server on port " + port
141 + ", it has already been used");
143 tracer
.error(name
+ ": cannot start server on port " + port
144 + ", it is already started");
149 * Will stop the server, synchronously and without a timeout.
152 tracer
.trace(name
+ ": stopping server");
160 * the maximum timeout to wait for existing actions to complete,
161 * or 0 for "no timeout"
163 * wait for the server to be stopped before returning
164 * (synchronous) or not (asynchronous)
166 public void stop(final long timeout
, final boolean wait
) {
170 new Thread(new Runnable() {
180 * Stop the server (synchronous).
183 * the maximum timeout to wait for existing actions to complete,
184 * or 0 for "no timeout"
186 private void stop(long timeout
) {
187 synchronized (lock
) {
188 if (started
&& !exiting
) {
192 new ConnectActionClient(createSocket(null, port
, ssl
)) {
194 public void action(Version serverVersion
)
200 while (ss
!= null && timeout
> 0 && timeout
> time
) {
204 } catch (Exception e
) {
206 counter
= 0; // will stop the main thread
212 // only return when stopped
213 while (started
|| exiting
) {
216 } catch (InterruptedException e
) {
225 tracer
.trace(name
+ ": server starting on port " + port
);
226 while (started
&& !exiting
) {
228 Socket s
= ss
.accept();
229 new ConnectActionServer(s
) {
230 private Version clientVersion
= new Version();
233 public void action(Version dummy
) throws Exception
{
235 for (Object data
= flush(); true; data
= flush()) {
238 rep
= onRequest(this, clientVersion
, data
);
239 } catch (Exception e
) {
244 } catch (NullPointerException e
) {
245 // Client has no data any more, we quit
250 public void connect() {
259 protected void onClientVersionReceived(Version clientVersion
) {
260 this.clientVersion
= clientVersion
;
265 // Will be covered by @link{Server#stop(long)} for timeouts
266 while (counter
> 0) {
269 } catch (Exception e
) {
276 } catch (Exception e
) {
289 * This is the method that is called on each client request.
291 * You are expected to react to it and return an answer (which can be NULL).
295 * @param clientVersion
298 * the data sent by the client (which can be NULL)
300 * @return the answer to return to the client (which can be NULL)
303 * in case of an exception, the error will only be logged
305 abstract protected Object
onRequest(ConnectActionServer action
,
306 Version clientVersion
, Object data
) throws Exception
;
309 * This method will be called on errors.
311 * By default, it will only call the trace handler (so you may want to call
312 * super {@link Server#onError} if you override it).
317 protected void onError(Exception e
) {
322 * Change the number of currently serviced actions.
325 * the number to increase or decrease
327 * @return the current number after this operation
329 private int count(int change
) {
330 synchronized (counterLock
) {
337 * Create a {@link Socket}.
340 * the host to connect to
342 * the port to connect to
344 * TRUE for SSL mode (or FALSE for plain text mode)
346 * @return the {@link Socket}
348 * @throws IOException
349 * in case of I/O error
351 static Socket
createSocket(String host
, int port
, boolean ssl
)
355 s
= SSLSocketFactory
.getDefault().createSocket(host
, port
);
356 ((SSLSocket
) s
).setEnabledCipherSuites(ANON_CIPHERS
);
358 s
= new Socket(host
, port
);
365 * Create a {@link ServerSocket}.
368 * the port to accept connections on
370 * TRUE for SSL mode (or FALSE for plain text mode)
372 * @return the {@link ServerSocket}
374 * @throws IOException
375 * in case of I/O error
377 static ServerSocket
createSocketServer(int port
, boolean ssl
)
381 ss
= SSLServerSocketFactory
.getDefault().createServerSocket(port
);
382 ((SSLServerSocket
) ss
).setEnabledCipherSuites(ANON_CIPHERS
);
384 ss
= new ServerSocket(port
);
391 * Return all the supported ciphers that do not use authentication.
393 * @return the list of such supported ciphers
395 private static String
[] getAnonCiphers() {
396 List
<String
> anonCiphers
= new ArrayList
<String
>();
397 for (String cipher
: ((SSLSocketFactory
) SSLSocketFactory
.getDefault())
398 .getSupportedCipherSuites()) {
399 if (cipher
.contains("_anon_")) {
400 anonCiphers
.add(cipher
);
404 return anonCiphers
.toArray(new String
[] {});