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 public void start() {
131 synchronized (lock
) {
132 if (!started
&& ss
!= null) {
134 new Thread(this).start();
140 tracer
.trace(name
+ ": server started on port " + port
);
141 } else if (ss
== null) {
142 tracer
.error(name
+ ": cannot start server on port " + port
143 + ", it has already been used");
145 tracer
.error(name
+ ": cannot start server on port " + port
146 + ", it is already started");
151 * Will stop the server, synchronously and without a timeout.
154 tracer
.trace(name
+ ": stopping server");
162 * the maximum timeout to wait for existing actions to complete,
163 * or 0 for "no timeout"
165 * wait for the server to be stopped before returning
166 * (synchronous) or not (asynchronous)
168 public void stop(final long timeout
, final boolean wait
) {
172 new Thread(new Runnable() {
182 * Stop the server (synchronous).
185 * the maximum timeout to wait for existing actions to complete,
186 * or 0 for "no timeout"
188 private void stop(long timeout
) {
189 synchronized (lock
) {
190 if (started
&& !exiting
) {
194 new ConnectActionClient(createSocket(null, port
, ssl
))
197 while (ss
!= null && timeout
> 0 && timeout
> time
) {
201 } catch (Exception e
) {
203 counter
= 0; // will stop the main thread
209 // only return when stopped
210 while (started
|| exiting
) {
213 } catch (InterruptedException e
) {
222 while (started
&& !exiting
) {
224 Socket s
= ss
.accept();
225 new ConnectActionServer(s
) {
227 public void action(Version clientVersion
) throws Exception
{
229 for (Object data
= rec(); true; data
= rec()) {
232 rep
= onRequest(this, clientVersion
, data
);
233 } catch (Exception e
) {
238 } catch (NullPointerException e
) {
239 // Client has no data any more, we quit
240 tracer
.trace("Client has data no more, stopping connection");
245 public void connect() {
255 // Will be covered by @link{Server#stop(long)} for timeouts
256 while (counter
> 0) {
259 } catch (Exception e
) {
266 } catch (Exception e
) {
279 * This is the method that is called on each client request.
281 * You are expected to react to it and return an answer (which can be NULL).
285 * @param clientVersion
288 * the data sent by the client (which can be NULL)
290 * @return the answer to return to the client (which can be NULL)
293 * in case of an exception, the error will only be logged
295 abstract protected Object
onRequest(ConnectActionServer action
,
296 Version clientVersion
, Object data
) throws Exception
;
299 * This method will be called on errors.
301 * By default, it will only call the trace handler (so you may want to call
302 * super {@link Server#onError} if you override it).
307 protected void onError(Exception e
) {
312 * Change the number of currently serviced actions.
315 * the number to increase or decrease
317 * @return the current number after this operation
319 private int count(int change
) {
320 synchronized (counterLock
) {
327 * Create a {@link Socket}.
330 * the host to connect to
332 * the port to connect to
334 * TRUE for SSL mode (or FALSE for plain text mode)
336 * @return the {@link Socket}
338 * @throws IOException
339 * in case of I/O error
341 static Socket
createSocket(String host
, int port
, boolean ssl
)
345 s
= SSLSocketFactory
.getDefault().createSocket(host
, port
);
346 ((SSLSocket
) s
).setEnabledCipherSuites(ANON_CIPHERS
);
348 s
= new Socket(host
, port
);
355 * Create a {@link ServerSocket}.
358 * the port to accept connections on
360 * TRUE for SSL mode (or FALSE for plain text mode)
362 * @return the {@link ServerSocket}
364 * @throws IOException
365 * in case of I/O error
367 static ServerSocket
createSocketServer(int port
, boolean ssl
)
371 ss
= SSLServerSocketFactory
.getDefault().createServerSocket(port
);
372 ((SSLServerSocket
) ss
).setEnabledCipherSuites(ANON_CIPHERS
);
374 ss
= new ServerSocket(port
);
381 * Return all the supported ciphers that do not use authentication.
383 * @return the list of such supported ciphers
385 private static String
[] getAnonCiphers() {
386 List
<String
> anonCiphers
= new ArrayList
<String
>();
387 for (String cipher
: ((SSLSocketFactory
) SSLSocketFactory
.getDefault())
388 .getSupportedCipherSuites()) {
389 if (cipher
.contains("_anon_")) {
390 anonCiphers
.add(cipher
);
394 return anonCiphers
.toArray(new String
[] {});