fr.quatrevieux.singleinstance.ipc.InstanceClient   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
eloc 21
c 1
b 0
f 0
dl 0
loc 40
ccs 15
cts 15
cp 1
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A InstanceClient(int) 0 2 1
A send(Message) 0 7 3
A close() 0 8 2
A open() 0 3 1
1
/*
2
 * This file is part of SingleInstance.
3
 *
4
 * SingleInstance is free software: you can redistribute it and/or modify
5
 * it under the terms of the GNU Lesser General Public License as published by
6
 * the Free Software Foundation, either version 3 of the License, or
7
 * (at your option) any later version.
8
 *
9
 * SingleInstance is distributed in the hope that it will be useful,
10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
 * GNU Lesser General Public License for more details.
13
 *
14
 * You should have received a copy of the GNU Lesser General Public License
15
 * along with SingleInstance.  If not, see <https://www.gnu.org/licenses/>.
16
 *
17
 * Copyright (c) 2020 Vincent Quatrevieux
18
 */
19
20
package fr.quatrevieux.singleinstance.ipc;
21
22
import java.io.Closeable;
23
import java.io.IOException;
24
import java.io.OutputStream;
25
import java.net.Socket;
26
27
/**
28
 * IPC client for sending actions to the distant instance
29
 *
30
 * Usage:
31
 * <pre>{@code
32
 *     try (InstanceClient client = new InstanceClient(1234)) {
33
 *         client.send("Hello", "my payload".getBytes());
34
 *     }
35
 * }</pre>
36
 */
37
final public class InstanceClient implements Closeable, MessageSender {
38
    final private int port;
39
    private Socket socket;
40
    private OutputStream output;
41
42
    /**
43
     * @param port The listening port
44
     */
45 1
    public InstanceClient(int port) {
46 1
        this.port = port;
47 1
    }
48
49
    /**
50
     * Open the client
51
     * Note: this method is implicitly called on {@link InstanceClient#send(Message)}
52
     *
53
     * @throws IOException When cannot open the socket
54
     */
55
    public void open() throws IOException {
56 1
        socket = new Socket("localhost", port);
57 1
        output = socket.getOutputStream();
58 1
    }
59
60
    @Override
61
    public void send(Message message) throws IOException {
62 1
        if (socket == null || socket.isClosed()) {
63 1
            open();
64
        }
65
66 1
        output.write(ProtocolParser.toBytes(message));
67 1
    }
68
69
    @Override
70
    public void close() throws IOException {
71 1
        if (socket != null) {
72 1
            output.close();
73 1
            output = null;
74
75 1
            socket.close();
76 1
            socket = null;
77
        }
78 1
    }
79
}
80