Fix Cache (URL to File could fail if no parent)
[nikiroo-utils.git] / src / be / nikiroo / utils / serial / server / ServerObject.java
CommitLineData
79ce1a49
NR
1package be.nikiroo.utils.serial.server;
2
3import java.io.IOException;
4import java.net.Socket;
5
6import be.nikiroo.utils.Version;
7
8/**
9 * This class implements a simple server that can listen for connections and
10 * send/receive objects.
11 * <p>
12 * Note: this {@link ServerObject} has to be discarded after use (cannot be
13 * started twice).
14 *
15 * @author niki
16 */
17abstract public class ServerObject extends Server {
18 /**
19 * Create a new server that will start listening on the network when
20 * {@link ServerObject#start()} is called.
21 *
22 * @param port
23 * the port to listen on, or 0 to assign any unallocated port
24 * found (which can later on be queried via
25 * {@link ServerObject#getPort()}
26 * @param ssl
27 * use a SSL connection (or not)
28 *
29 * @throws IOException
30 * in case of I/O error
31 */
32 public ServerObject(int port, boolean ssl) throws IOException {
33 super(port, ssl);
34 }
35
36 /**
37 * Create a new server that will start listening on the network when
38 * {@link ServerObject#start()} is called.
39 *
40 * @param name
41 * the server name (only used for debug info and traces)
42 * @param port
43 * the port to listen on
44 * @param ssl
45 * use a SSL connection (or not)
46 *
47 * @throws IOException
48 * in case of I/O error
49 */
50 public ServerObject(String name, int port, boolean ssl) throws IOException {
51 super(name, port, ssl);
52 }
53
54 @Override
55 protected ConnectActionServer createConnectActionServer(Socket s) {
56 return new ConnectActionServerObject(s) {
57 @Override
58 public void action(Version clientVersion) throws Exception {
59 try {
60 for (Object data = rec(); true; data = rec()) {
61 Object rep = null;
62 try {
63 rep = onRequest(this, clientVersion, data);
64 } catch (Exception e) {
65 onError(e);
66 }
67 send(rep);
68 }
69 } catch (NullPointerException e) {
70 // Client has no data any more, we quit
79ce1a49
NR
71 }
72 }
0ff71477
NR
73
74 @Override
75 protected void onError(Exception e) {
d827da2a 76 ServerObject.this.onError(e);
0ff71477 77 }
79ce1a49
NR
78 };
79 }
80
81 /**
82 * This is the method that is called on each client request.
83 * <p>
84 * You are expected to react to it and return an answer (which can be NULL).
85 *
86 * @param action
87 * the client action
88 * @param clientVersion
89 * the client version
90 * @param data
91 * the data sent by the client (which can be NULL)
92 *
93 * @return the answer to return to the client (which can be NULL)
94 *
95 * @throws Exception
96 * in case of an exception, the error will only be logged
97 */
98 abstract protected Object onRequest(ConnectActionServerObject action,
99 Version clientVersion, Object data) throws Exception;
100}