...
[nikiroo-utils.git] / src / be / nikiroo / utils / serial / server / ConnectActionClient.java
1 package be.nikiroo.utils.serial.server;
2
3 import java.io.IOException;
4 import java.net.Socket;
5 import java.net.UnknownHostException;
6
7 /**
8 * Base class used for the client basic handling.
9 * <p>
10 * It represents a single action: a client is expected to only execute one
11 * action.
12 *
13 * @author niki
14 */
15 abstract class ConnectActionClient {
16 /**
17 * The underlying {@link ConnectAction}.
18 * <p>
19 * Cannot be NULL.
20 */
21 protected ConnectAction action;
22
23 /**
24 * Create a new {@link ConnectActionClient}.
25 *
26 * @param host
27 * the host to bind to
28 * @param port
29 * the port to bind to
30 * @param key
31 * an optional key to encrypt all the communications (if NULL,
32 * everything will be sent in clear text)
33 *
34 * @throws IOException
35 * in case of I/O error
36 * @throws UnknownHostException
37 * if the host is not known
38 * @throws IllegalArgumentException
39 * if the port parameter is outside the specified range of valid
40 * port values, which is between 0 and 65535, inclusive
41 */
42 public ConnectActionClient(String host, int port, String key)
43 throws IOException {
44 this(new Socket(host, port), key);
45 }
46
47 /**
48 * Create a new {@link ConnectActionClient}.
49 *
50 * @param s
51 * the socket to bind to
52 * @param key
53 * an optional key to encrypt all the communications (if NULL,
54 * everything will be sent in clear text)
55 */
56 public ConnectActionClient(Socket s, String key) {
57 action = new ConnectAction(s, false, key) {
58 @Override
59 protected void action() throws Exception {
60 ConnectActionClient.this.action();
61 }
62
63 @Override
64 protected void onError(Exception e) {
65 ConnectActionClient.this.onError(e);
66 }
67 };
68 }
69
70 /**
71 * Actually start the process and call the action (synchronous).
72 */
73 public void connect() {
74 action.connect();
75 }
76
77 /**
78 * Actually start the process and call the action (asynchronous).
79 */
80 public void connectAsync() {
81 new Thread(new Runnable() {
82 @Override
83 public void run() {
84 connect();
85 }
86 }).start();
87 }
88
89 /**
90 * Method that will be called when an action is performed on the client.
91 *
92 * @throws Exception
93 * in case of I/O error
94 */
95 @SuppressWarnings("unused")
96 public void action() throws Exception {
97 }
98
99 /**
100 * Handler called when an unexpected error occurs in the code.
101 * <p>
102 * Will just ignore the error by default.
103 *
104 * @param e
105 * the exception that occurred
106 */
107 protected void onError(@SuppressWarnings("unused") Exception e) {
108 }
109 }