-
Notifications
You must be signed in to change notification settings - Fork 89
/
Copy pathUnixDomainSocketTest.java
83 lines (68 loc) · 2.36 KB
/
UnixDomainSocketTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import java.io.IOException;
import java.net.StandardProtocolFamily;
import java.net.UnixDomainSocketAddress;
import java.nio.channels.*;
import java.nio.*;
import java.nio.file.*;
import java.rmi.server.SocketSecurityException;
public class UnixDomainSocketTest {
private static final String SOCKET_PATH = "server.socket";
public static void main(String[] args) throws Exception {
var socketFile = Path.of(System.getProperty("user.home")).resolve(SOCKET_PATH);
var address = UnixDomainSocketAddress.of(socketFile);
Thread.sleep(500);
new Thread(new ServerProcess(address)).start();
Thread.sleep(1000);
new Thread(new ClientProcess(address)).start();
Thread.currentThread().join(10_000);
}
}
class ServerProcess implements Runnable {
private final UnixDomainSocketAddress address;
ServerProcess(UnixDomainSocketAddress address) {
this.address = address;
}
public void run() {
try (ServerSocketChannel server = ServerSocketChannel.open(StandardProtocolFamily.UNIX)) {
server.bind(this.address);
System.out.println("[Server] starting");
SocketChannel channel = server.accept();
System.out.println("[Server] sending message");
channel.write(ByteBuffer.wrap("Hello client!".getBytes()));
var buffer = ByteBuffer.allocate(1024);
var length = channel.read(buffer);
if (length > 0) {
System.out.println("[Server] message from client: " + new String(buffer.array()));
} else {
System.out.println("[Server] empty");
}
channel.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
class ClientProcess implements Runnable {
private final UnixDomainSocketAddress address;
ClientProcess(UnixDomainSocketAddress address) {
this.address = address;
}
public void run() {
try (SocketChannel client = SocketChannel.open(StandardProtocolFamily.UNIX)) {
System.out.println("[Client] starting");
client.connect(this.address);
System.out.println("[Client] reading message");
var buffer = ByteBuffer.allocate(1024);
var length = client.read(buffer);
if (length > 0) {
System.out.println("[Client] message from the server: " + new String(buffer.array()));
} else {
System.out.println("[Client] empty");
}
System.out.println("[Client] sending message");
client.write(ByteBuffer.wrap("Hello server, I'm your new client!".getBytes()));
} catch (IOException ex) {
ex.printStackTrace();
}
}
}