-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnixDomainSocketDemo.java
More file actions
187 lines (155 loc) · 6.68 KB
/
Copy pathUnixDomainSocketDemo.java
File metadata and controls
187 lines (155 loc) · 6.68 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
package java16.unixsocket;
import java.io.IOException;
import java.net.StandardProtocolFamily;
import java.net.UnixDomainSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
/**
* Java 16 Unix-Domain Socket Channels
* Demonstrates inter-process communication using Unix-domain sockets
*
* NOTE: Unix-domain sockets only work on Unix-like systems (Linux, macOS)
* This example demonstrates the API structure
*/
public class UnixDomainSocketDemo {
private static final String SOCKET_PATH = "/tmp/java16_unix_socket";
public static void main(String[] args) {
System.out.println("=== Java 16 Unix-Domain Socket Channels ===\n");
// Check if running on Unix-like system
String os = System.getProperty("os.name").toLowerCase();
if (!os.contains("nix") && !os.contains("nux") && !os.contains("mac")) {
System.out.println("Unix-domain sockets are only available on Unix-like systems.");
System.out.println("Current OS: " + System.getProperty("os.name"));
System.out.println("\nExample usage:");
demonstrateAPI();
return;
}
// Run server in a separate thread
Thread serverThread = new Thread(() -> {
try {
runServer();
} catch (IOException e) {
System.err.println("Server error: " + e.getMessage());
}
});
serverThread.start();
// Wait for server to start
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
// Run client
try {
runClient();
} catch (IOException e) {
System.err.println("Client error: " + e.getMessage());
}
// Cleanup
try {
serverThread.join();
cleanup();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
private static void runServer() throws IOException {
System.out.println("Starting server...");
// Create server socket channel
ServerSocketChannel server = ServerSocketChannel.open(StandardProtocolFamily.UNIX);
// Create socket address
UnixDomainSocketAddress address = UnixDomainSocketAddress.of(SOCKET_PATH);
// Bind to address
server.bind(address);
System.out.println("Server bound to: " + SOCKET_PATH);
// Accept connection
SocketChannel client = server.accept();
System.out.println("Client connected");
// Read message from client
ByteBuffer buffer = ByteBuffer.allocate(1024);
int bytesRead = client.read(buffer);
if (bytesRead > 0) {
buffer.flip();
String message = StandardCharsets.UTF_8.decode(buffer).toString();
System.out.println("Received from client: " + message);
// Send response
String response = "Hello from server!";
ByteBuffer responseBuffer = ByteBuffer.wrap(response.getBytes(StandardCharsets.UTF_8));
client.write(responseBuffer);
System.out.println("Sent response to client");
}
// Close connections
client.close();
server.close();
System.out.println("Server closed");
}
private static void runClient() throws IOException {
System.out.println("\nStarting client...");
// Create client socket channel
SocketChannel client = SocketChannel.open(StandardProtocolFamily.UNIX);
// Connect to server
UnixDomainSocketAddress address = UnixDomainSocketAddress.of(SOCKET_PATH);
client.connect(address);
System.out.println("Connected to server");
// Send message
String message = "Hello from client!";
ByteBuffer buffer = ByteBuffer.wrap(message.getBytes(StandardCharsets.UTF_8));
client.write(buffer);
System.out.println("Sent message to server");
// Read response
ByteBuffer responseBuffer = ByteBuffer.allocate(1024);
int bytesRead = client.read(responseBuffer);
if (bytesRead > 0) {
responseBuffer.flip();
String response = StandardCharsets.UTF_8.decode(responseBuffer).toString();
System.out.println("Received from server: " + response);
}
// Close connection
client.close();
System.out.println("Client closed");
}
private static void cleanup() {
try {
Path socketPath = Path.of(SOCKET_PATH);
if (Files.exists(socketPath)) {
Files.delete(socketPath);
System.out.println("\nCleaned up socket file");
}
} catch (IOException e) {
System.err.println("Cleanup error: " + e.getMessage());
}
}
private static void demonstrateAPI() {
System.out.println("""
// Server side
ServerSocketChannel server = ServerSocketChannel.open(StandardProtocolFamily.UNIX);
UnixDomainSocketAddress address = UnixDomainSocketAddress.of("/tmp/mysocket");
server.bind(address);
SocketChannel client = server.accept();
// Client side
SocketChannel client = SocketChannel.open(StandardProtocolFamily.UNIX);
UnixDomainSocketAddress address = UnixDomainSocketAddress.of("/tmp/mysocket");
client.connect(address);
// Send data
ByteBuffer buffer = ByteBuffer.wrap("Hello".getBytes());
client.write(buffer);
// Receive data
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
client.read(readBuffer);
""");
System.out.println("\nKey Features:");
System.out.println("- File-based addressing (uses file system paths)");
System.out.println("- Local communication only (same machine)");
System.out.println("- Lower overhead than TCP/IP");
System.out.println("- File system permissions control access");
System.out.println("\nUse Cases:");
System.out.println("- Inter-process communication on Unix systems");
System.out.println("- Docker container communication");
System.out.println("- Microservices on same host");
System.out.println("- Application-to-daemon communication");
}
}