0
# Unix Domain Sockets
1
2
Unix Domain Socket implementation providing high-performance inter-process communication using file system paths. Supports both traditional socket APIs and streaming I/O operations.
3
4
## Core Imports
5
6
```java
7
import java.io.*;
8
import java.net.*;
9
import org.newsclub.net.unix.AFUNIXSocket;
10
import org.newsclub.net.unix.AFUNIXServerSocket;
11
import org.newsclub.net.unix.AFUNIXSocketAddress;
12
import org.newsclub.net.unix.AFUNIXSocketCredentials;
13
import org.newsclub.net.unix.AFUNIXSocketExtensions;
14
import org.newsclub.net.unix.AFUNIXSocketChannel;
15
import org.newsclub.net.unix.AFUNIXServerSocketChannel;
16
```
17
18
## Capabilities
19
20
### AFUNIXSocket
21
22
Client-side Unix Domain Socket implementation for establishing connections to socket servers.
23
24
```java { .api }
25
/**
26
* Unix Domain Socket client implementation
27
*/
28
public final class AFUNIXSocket extends AFSocket implements AFUNIXSocketExtensions {
29
30
/**
31
* Creates a new AFUNIXSocket and connects it to the specified address
32
* @param addr The socket address to connect to
33
* @return Connected AFUNIXSocket instance
34
* @throws IOException if connection fails
35
*/
36
public static AFUNIXSocket connectTo(AFUNIXSocketAddress addr) throws IOException;
37
38
/**
39
* Creates a new unconnected AFUNIXSocket
40
* @return New AFUNIXSocket instance
41
* @throws IOException if socket creation fails
42
*/
43
public static AFUNIXSocket newInstance() throws IOException;
44
45
/**
46
* Creates a new unconnected strict AFUNIXSocket
47
* @return New strict AFUNIXSocket instance
48
* @throws IOException if socket creation fails
49
*/
50
public static AFUNIXSocket newStrictInstance() throws IOException;
51
52
/**
53
* Creates a new AFUNIXSocket connected to the given file
54
* @param socketFile The socket file to connect to
55
* @return Connected AFUNIXSocket instance
56
* @throws IOException if connection fails
57
*/
58
public static AFUNIXSocket connectTo(File socketFile) throws IOException;
59
60
// Socket operations
61
public void connect(SocketAddress endpoint) throws IOException;
62
public void connect(SocketAddress endpoint, int timeout) throws IOException;
63
public void bind(SocketAddress bindpoint) throws IOException;
64
65
// Stream access
66
public InputStream getInputStream() throws IOException;
67
public OutputStream getOutputStream() throws IOException;
68
69
// Socket properties
70
public boolean isClosed();
71
public boolean isConnected();
72
public boolean isBound();
73
74
// Connection validation
75
public boolean checkConnectionClosed() throws IOException;
76
77
// AFUNIXSocketExtensions interface methods
78
79
/**
80
* Gets file descriptors received via ancillary messages
81
* @return Array of received file descriptors
82
* @throws IOException if retrieval fails
83
*/
84
public FileDescriptor[] getReceivedFileDescriptors() throws IOException;
85
86
/**
87
* Clears the queue of received file descriptors
88
*/
89
public void clearReceivedFileDescriptors();
90
91
/**
92
* Sets file descriptors to be sent via ancillary messages
93
* @param fds File descriptors to send
94
* @throws IOException if setting fails
95
*/
96
public void setOutboundFileDescriptors(FileDescriptor... fds) throws IOException;
97
98
/**
99
* Checks if outbound file descriptors are pending
100
* @return true if file descriptors are queued for sending
101
*/
102
public boolean hasOutboundFileDescriptors();
103
104
/**
105
* Gets credentials of the peer process
106
* @return Peer credentials information
107
* @throws IOException if retrieval fails
108
*/
109
public AFUNIXSocketCredentials getPeerCredentials() throws IOException;
110
111
// NIO Channel access
112
113
/**
114
* Returns the associated NIO channel for this socket
115
* @return AFUNIXSocketChannel instance
116
*/
117
public AFUNIXSocketChannel getChannel();
118
}
119
```
120
121
**Usage Examples:**
122
123
```java
124
import java.io.*;
125
import java.nio.charset.StandardCharsets;
126
import org.newsclub.net.unix.*;
127
128
// Connect to existing socket server
129
File socketFile = new File("/tmp/app.sock");
130
try (AFUNIXSocket socket = AFUNIXSocket.connectTo(AFUNIXSocketAddress.of(socketFile))) {
131
132
// Send data
133
OutputStream os = socket.getOutputStream();
134
os.write("Hello Server".getBytes(StandardCharsets.UTF_8));
135
os.flush();
136
137
// Receive response
138
InputStream is = socket.getInputStream();
139
byte[] buffer = new byte[1024];
140
int bytesRead = is.read(buffer);
141
String response = new String(buffer, 0, bytesRead, StandardCharsets.UTF_8);
142
System.out.println("Server response: " + response);
143
}
144
145
// Alternative connection method
146
try (AFUNIXSocket socket = AFUNIXSocket.connectTo(socketFile)) {
147
// Connection established using File directly
148
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
149
DataInputStream dis = new DataInputStream(socket.getInputStream());
150
151
// Exchange binary data
152
dos.writeInt(42);
153
dos.writeUTF("test message");
154
dos.flush();
155
156
int responseValue = dis.readInt();
157
String responseMessage = dis.readUTF();
158
}
159
```
160
161
### AFUNIXServerSocket
162
163
Server-side Unix Domain Socket implementation for accepting client connections and managing socket servers.
164
165
```java { .api }
166
/**
167
* Unix Domain Socket server implementation
168
*/
169
public final class AFUNIXServerSocket extends AFServerSocket {
170
171
/**
172
* Creates a new AFUNIXServerSocket
173
* @return New AFUNIXServerSocket instance
174
* @throws IOException if server socket creation fails
175
*/
176
public static AFUNIXServerSocket newInstance() throws IOException;
177
178
/**
179
* Creates a server socket bound to the specified address
180
* @param addr The address to bind to
181
* @return Bound AFUNIXServerSocket instance
182
* @throws IOException if binding fails
183
*/
184
public static AFUNIXServerSocket bindOn(AFUNIXSocketAddress addr) throws IOException;
185
186
/**
187
* Creates a server socket bound to the specified file
188
* @param socketFile The socket file to bind to
189
* @return Bound AFUNIXServerSocket instance
190
* @throws IOException if binding fails
191
*/
192
public static AFUNIXServerSocket bindOn(File socketFile) throws IOException;
193
194
/**
195
* Creates a server socket bound to the specified address with delete-on-close
196
* @param addr The address to bind to
197
* @param deleteOnClose Whether to delete socket file on close
198
* @return Bound AFUNIXServerSocket instance
199
* @throws IOException if binding fails
200
*/
201
public static AFUNIXServerSocket bindOn(AFUNIXSocketAddress addr, boolean deleteOnClose) throws IOException;
202
203
// Server operations
204
public void bind(SocketAddress endpoint) throws IOException;
205
public void bind(SocketAddress endpoint, int backlog) throws IOException;
206
public AFUNIXSocket accept() throws IOException;
207
208
// Server properties
209
public boolean isClosed();
210
public boolean isBound();
211
public AFUNIXSocketAddress getLocalSocketAddress();
212
213
// Configuration
214
public void setReuseAddress(boolean on) throws SocketException;
215
public boolean getReuseAddress() throws SocketException;
216
public void setSoTimeout(int timeout) throws SocketException;
217
public int getSoTimeout() throws IOException;
218
219
// NIO Channel access
220
221
/**
222
* Returns the associated NIO channel for this server socket
223
* @return AFUNIXServerSocketChannel instance
224
*/
225
public AFUNIXServerSocketChannel getChannel();
226
}
227
```
228
229
**Usage Examples:**
230
231
```java
232
import java.io.*;
233
import java.nio.charset.StandardCharsets;
234
import org.newsclub.net.unix.*;
235
236
// Basic server setup
237
File socketFile = new File("/tmp/server.sock");
238
try (AFUNIXServerSocket server = AFUNIXServerSocket.newInstance()) {
239
server.bind(AFUNIXSocketAddress.of(socketFile));
240
System.out.println("Server listening on: " + socketFile);
241
242
// Accept connections in loop
243
while (!Thread.interrupted()) {
244
try (AFUNIXSocket clientSocket = server.accept()) {
245
handleClient(clientSocket);
246
} catch (IOException e) {
247
System.err.println("Error handling client: " + e.getMessage());
248
}
249
}
250
}
251
252
// Server with configuration
253
try (AFUNIXServerSocket server = AFUNIXServerSocket.newInstance()) {
254
server.setReuseAddress(true); // Enable address reuse
255
server.setSoTimeout(30000); // 30 second timeout
256
257
server.bind(AFUNIXSocketAddress.of(socketFile), 50); // backlog of 50
258
259
// Handle single client
260
try (AFUNIXSocket client = server.accept();
261
InputStream is = client.getInputStream();
262
OutputStream os = client.getOutputStream()) {
263
264
// Echo server implementation
265
byte[] buffer = new byte[1024];
266
int bytesRead = is.read(buffer);
267
os.write(buffer, 0, bytesRead);
268
os.flush();
269
}
270
}
271
272
// Helper method for client handling
273
private static void handleClient(AFUNIXSocket clientSocket) throws IOException {
274
try (InputStream is = clientSocket.getInputStream();
275
OutputStream os = clientSocket.getOutputStream();
276
BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
277
PrintWriter writer = new PrintWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8), true)) {
278
279
String line;
280
while ((line = reader.readLine()) != null) {
281
// Echo back with prefix
282
writer.println("ECHO: " + line);
283
284
if ("quit".equalsIgnoreCase(line.trim())) {
285
break;
286
}
287
}
288
}
289
}
290
```
291
292
### AFUNIXDatagramSocket
293
294
Datagram-based Unix Domain Socket implementation for connectionless packet communication.
295
296
```java { .api }
297
/**
298
* Unix Domain Datagram socket implementation
299
*/
300
public final class AFUNIXDatagramSocket extends AFDatagramSocket {
301
302
/**
303
* Creates a new AFUNIXDatagramSocket
304
* @return New AFUNIXDatagramSocket instance
305
* @throws SocketException if socket creation fails
306
*/
307
public static AFUNIXDatagramSocket newInstance() throws SocketException;
308
309
/**
310
* Creates a datagram socket bound to the specified address
311
* @param addr The address to bind to
312
* @return Bound AFUNIXDatagramSocket instance
313
* @throws SocketException if binding fails
314
*/
315
public static AFUNIXDatagramSocket bindOn(AFUNIXSocketAddress addr) throws SocketException;
316
317
// Datagram operations
318
public void send(DatagramPacket p) throws IOException;
319
public void receive(DatagramPacket p) throws IOException;
320
public void connect(SocketAddress addr) throws SocketException;
321
public void disconnect();
322
323
// Socket configuration
324
public void bind(SocketAddress addr) throws SocketException;
325
public AFUNIXSocketAddress getLocalSocketAddress();
326
public AFUNIXSocketAddress getRemoteSocketAddress();
327
}
328
```
329
330
**Usage Examples:**
331
332
```java
333
import java.net.DatagramPacket;
334
import java.nio.charset.StandardCharsets;
335
import org.newsclub.net.unix.*;
336
337
// Datagram sender
338
File targetSocket = new File("/tmp/datagram-receiver.sock");
339
try (AFUNIXDatagramSocket sender = AFUNIXDatagramSocket.newInstance()) {
340
String message = "Hello via datagram";
341
byte[] data = message.getBytes(StandardCharsets.UTF_8);
342
343
DatagramPacket packet = new DatagramPacket(
344
data, data.length, AFUNIXSocketAddress.of(targetSocket)
345
);
346
347
sender.send(packet);
348
}
349
350
// Datagram receiver
351
File receiverSocket = new File("/tmp/datagram-receiver.sock");
352
try (AFUNIXDatagramSocket receiver = AFUNIXDatagramSocket.bindOn(AFUNIXSocketAddress.of(receiverSocket))) {
353
354
byte[] buffer = new byte[1024];
355
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
356
357
receiver.receive(packet);
358
359
String receivedMessage = new String(packet.getData(), 0, packet.getLength(), StandardCharsets.UTF_8);
360
System.out.println("Received: " + receivedMessage);
361
System.out.println("From: " + packet.getSocketAddress());
362
}
363
```
364
365
## Socket Configuration
366
367
### Connection Options
368
369
```java { .api }
370
// Socket timeout configuration
371
public void setSoTimeout(int timeout) throws SocketException;
372
public int getSoTimeout() throws SocketException;
373
374
// Keep-alive configuration
375
public void setKeepAlive(boolean on) throws SocketException;
376
public boolean getKeepAlive() throws SocketException;
377
378
// Buffer size configuration
379
public void setReceiveBufferSize(int size) throws SocketException;
380
public int getReceiveBufferSize() throws SocketException;
381
public void setSendBufferSize(int size) throws SocketException;
382
public int getSendBufferSize() throws SocketException;
383
```
384
385
### Advanced Features
386
387
```java { .api }
388
// Connection validation
389
public boolean checkConnectionClosed() throws IOException;
390
391
// File descriptor access
392
public FileDescriptor getFileDescriptor() throws IOException;
393
394
// Peer credentials (Linux/macOS)
395
public PeerCredentials getPeerCredentials() throws IOException;
396
```
397
398
## Error Handling
399
400
Common exceptions when working with Unix Domain Sockets:
401
402
```java { .api }
403
// Socket-specific exceptions
404
public class AFException extends IOException;
405
public class SocketClosedException extends SocketException;
406
public class AddressUnavailableSocketException extends SocketException;
407
public class BrokenPipeSocketException extends SocketException;
408
public class ConnectionResetSocketException extends SocketException;
409
```
410
411
**Error Handling Examples:**
412
413
```java
414
try {
415
AFUNIXSocket socket = AFUNIXSocket.connectTo(AFUNIXSocketAddress.of(socketFile));
416
// Use socket...
417
} catch (AddressUnavailableSocketException e) {
418
System.err.println("Socket file does not exist or server not running");
419
} catch (ConnectionResetSocketException e) {
420
System.err.println("Connection was reset by peer");
421
} catch (BrokenPipeSocketException e) {
422
System.err.println("Broken pipe - peer closed connection");
423
} catch (SocketClosedException e) {
424
System.err.println("Attempted operation on closed socket");
425
} catch (IOException e) {
426
System.err.println("General I/O error: " + e.getMessage());
427
}
428
```