CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-com-kohlschutter-junixsocket--junixsocket-core

Java Unix Domain Socket implementation providing AF_UNIX, AF_TIPC, AF_VSOCK, and AF_SYSTEM socket support with traditional and NIO APIs

Pending
Overview
Eval results
Files

unix-sockets.mddocs/

Unix Domain Sockets

Unix Domain Socket implementation providing high-performance inter-process communication using file system paths. Supports both traditional socket APIs and streaming I/O operations.

Core Imports

import java.io.*;
import java.net.*;
import org.newsclub.net.unix.AFUNIXSocket;
import org.newsclub.net.unix.AFUNIXServerSocket;
import org.newsclub.net.unix.AFUNIXSocketAddress;
import org.newsclub.net.unix.AFUNIXSocketCredentials;
import org.newsclub.net.unix.AFUNIXSocketExtensions;
import org.newsclub.net.unix.AFUNIXSocketChannel;
import org.newsclub.net.unix.AFUNIXServerSocketChannel;

Capabilities

AFUNIXSocket

Client-side Unix Domain Socket implementation for establishing connections to socket servers.

/**
 * Unix Domain Socket client implementation
 */
public final class AFUNIXSocket extends AFSocket implements AFUNIXSocketExtensions {
    
    /**
     * Creates a new AFUNIXSocket and connects it to the specified address
     * @param addr The socket address to connect to
     * @return Connected AFUNIXSocket instance
     * @throws IOException if connection fails
     */
    public static AFUNIXSocket connectTo(AFUNIXSocketAddress addr) throws IOException;
    
    /**
     * Creates a new unconnected AFUNIXSocket
     * @return New AFUNIXSocket instance
     * @throws IOException if socket creation fails
     */
    public static AFUNIXSocket newInstance() throws IOException;
    
    /**
     * Creates a new unconnected strict AFUNIXSocket
     * @return New strict AFUNIXSocket instance
     * @throws IOException if socket creation fails
     */
    public static AFUNIXSocket newStrictInstance() throws IOException;
    
    /**
     * Creates a new AFUNIXSocket connected to the given file
     * @param socketFile The socket file to connect to
     * @return Connected AFUNIXSocket instance
     * @throws IOException if connection fails
     */
    public static AFUNIXSocket connectTo(File socketFile) throws IOException;
    
    // Socket operations
    public void connect(SocketAddress endpoint) throws IOException;
    public void connect(SocketAddress endpoint, int timeout) throws IOException;
    public void bind(SocketAddress bindpoint) throws IOException;
    
    // Stream access
    public InputStream getInputStream() throws IOException;
    public OutputStream getOutputStream() throws IOException;
    
    // Socket properties
    public boolean isClosed();
    public boolean isConnected();
    public boolean isBound();
    
    // Connection validation
    public boolean checkConnectionClosed() throws IOException;
    
    // AFUNIXSocketExtensions interface methods
    
    /**
     * Gets file descriptors received via ancillary messages
     * @return Array of received file descriptors
     * @throws IOException if retrieval fails
     */
    public FileDescriptor[] getReceivedFileDescriptors() throws IOException;
    
    /**
     * Clears the queue of received file descriptors
     */
    public void clearReceivedFileDescriptors();
    
    /**
     * Sets file descriptors to be sent via ancillary messages
     * @param fds File descriptors to send
     * @throws IOException if setting fails
     */
    public void setOutboundFileDescriptors(FileDescriptor... fds) throws IOException;
    
    /**
     * Checks if outbound file descriptors are pending
     * @return true if file descriptors are queued for sending
     */
    public boolean hasOutboundFileDescriptors();
    
    /**
     * Gets credentials of the peer process
     * @return Peer credentials information
     * @throws IOException if retrieval fails
     */
    public AFUNIXSocketCredentials getPeerCredentials() throws IOException;
    
    // NIO Channel access
    
    /**
     * Returns the associated NIO channel for this socket
     * @return AFUNIXSocketChannel instance
     */
    public AFUNIXSocketChannel getChannel();
}

Usage Examples:

import java.io.*;
import java.nio.charset.StandardCharsets;
import org.newsclub.net.unix.*;

// Connect to existing socket server
File socketFile = new File("/tmp/app.sock");
try (AFUNIXSocket socket = AFUNIXSocket.connectTo(AFUNIXSocketAddress.of(socketFile))) {
    
    // Send data
    OutputStream os = socket.getOutputStream();
    os.write("Hello Server".getBytes(StandardCharsets.UTF_8));
    os.flush();
    
    // Receive response
    InputStream is = socket.getInputStream();
    byte[] buffer = new byte[1024];
    int bytesRead = is.read(buffer);
    String response = new String(buffer, 0, bytesRead, StandardCharsets.UTF_8);
    System.out.println("Server response: " + response);
}

// Alternative connection method
try (AFUNIXSocket socket = AFUNIXSocket.connectTo(socketFile)) {
    // Connection established using File directly
    DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
    DataInputStream dis = new DataInputStream(socket.getInputStream());
    
    // Exchange binary data
    dos.writeInt(42);
    dos.writeUTF("test message");
    dos.flush();
    
    int responseValue = dis.readInt();
    String responseMessage = dis.readUTF();
}

AFUNIXServerSocket

Server-side Unix Domain Socket implementation for accepting client connections and managing socket servers.

/**
 * Unix Domain Socket server implementation
 */
public final class AFUNIXServerSocket extends AFServerSocket {
    
    /**
     * Creates a new AFUNIXServerSocket
     * @return New AFUNIXServerSocket instance
     * @throws IOException if server socket creation fails
     */
    public static AFUNIXServerSocket newInstance() throws IOException;
    
    /**
     * Creates a server socket bound to the specified address
     * @param addr The address to bind to
     * @return Bound AFUNIXServerSocket instance
     * @throws IOException if binding fails
     */
    public static AFUNIXServerSocket bindOn(AFUNIXSocketAddress addr) throws IOException;
    
    /**
     * Creates a server socket bound to the specified file
     * @param socketFile The socket file to bind to
     * @return Bound AFUNIXServerSocket instance
     * @throws IOException if binding fails
     */
    public static AFUNIXServerSocket bindOn(File socketFile) throws IOException;
    
    /**
     * Creates a server socket bound to the specified address with delete-on-close
     * @param addr The address to bind to
     * @param deleteOnClose Whether to delete socket file on close
     * @return Bound AFUNIXServerSocket instance
     * @throws IOException if binding fails
     */
    public static AFUNIXServerSocket bindOn(AFUNIXSocketAddress addr, boolean deleteOnClose) throws IOException;
    
    // Server operations
    public void bind(SocketAddress endpoint) throws IOException;
    public void bind(SocketAddress endpoint, int backlog) throws IOException;
    public AFUNIXSocket accept() throws IOException;
    
    // Server properties
    public boolean isClosed();
    public boolean isBound();
    public AFUNIXSocketAddress getLocalSocketAddress();
    
    // Configuration
    public void setReuseAddress(boolean on) throws SocketException;
    public boolean getReuseAddress() throws SocketException;
    public void setSoTimeout(int timeout) throws SocketException;
    public int getSoTimeout() throws IOException;
    
    // NIO Channel access
    
    /**
     * Returns the associated NIO channel for this server socket
     * @return AFUNIXServerSocketChannel instance
     */
    public AFUNIXServerSocketChannel getChannel();
}

Usage Examples:

import java.io.*;
import java.nio.charset.StandardCharsets;
import org.newsclub.net.unix.*;

// Basic server setup
File socketFile = new File("/tmp/server.sock");
try (AFUNIXServerSocket server = AFUNIXServerSocket.newInstance()) {
    server.bind(AFUNIXSocketAddress.of(socketFile));
    System.out.println("Server listening on: " + socketFile);
    
    // Accept connections in loop
    while (!Thread.interrupted()) {
        try (AFUNIXSocket clientSocket = server.accept()) {
            handleClient(clientSocket);
        } catch (IOException e) {
            System.err.println("Error handling client: " + e.getMessage());
        }
    }
}

// Server with configuration
try (AFUNIXServerSocket server = AFUNIXServerSocket.newInstance()) {
    server.setReuseAddress(true);  // Enable address reuse
    server.setSoTimeout(30000);    // 30 second timeout
    
    server.bind(AFUNIXSocketAddress.of(socketFile), 50);  // backlog of 50
    
    // Handle single client
    try (AFUNIXSocket client = server.accept();
         InputStream is = client.getInputStream();
         OutputStream os = client.getOutputStream()) {
        
        // Echo server implementation
        byte[] buffer = new byte[1024];
        int bytesRead = is.read(buffer);
        os.write(buffer, 0, bytesRead);
        os.flush();
    }
}

// Helper method for client handling
private static void handleClient(AFUNIXSocket clientSocket) throws IOException {
    try (InputStream is = clientSocket.getInputStream();
         OutputStream os = clientSocket.getOutputStream();
         BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
         PrintWriter writer = new PrintWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8), true)) {
        
        String line;
        while ((line = reader.readLine()) != null) {
            // Echo back with prefix
            writer.println("ECHO: " + line);
            
            if ("quit".equalsIgnoreCase(line.trim())) {
                break;
            }
        }
    }
}

AFUNIXDatagramSocket

Datagram-based Unix Domain Socket implementation for connectionless packet communication.

/**
 * Unix Domain Datagram socket implementation
 */
public final class AFUNIXDatagramSocket extends AFDatagramSocket {
    
    /**
     * Creates a new AFUNIXDatagramSocket
     * @return New AFUNIXDatagramSocket instance
     * @throws SocketException if socket creation fails
     */
    public static AFUNIXDatagramSocket newInstance() throws SocketException;
    
    /**
     * Creates a datagram socket bound to the specified address
     * @param addr The address to bind to
     * @return Bound AFUNIXDatagramSocket instance
     * @throws SocketException if binding fails
     */
    public static AFUNIXDatagramSocket bindOn(AFUNIXSocketAddress addr) throws SocketException;
    
    // Datagram operations
    public void send(DatagramPacket p) throws IOException;
    public void receive(DatagramPacket p) throws IOException;
    public void connect(SocketAddress addr) throws SocketException;
    public void disconnect();
    
    // Socket configuration
    public void bind(SocketAddress addr) throws SocketException;
    public AFUNIXSocketAddress getLocalSocketAddress();
    public AFUNIXSocketAddress getRemoteSocketAddress();
}

Usage Examples:

import java.net.DatagramPacket;
import java.nio.charset.StandardCharsets;
import org.newsclub.net.unix.*;

// Datagram sender
File targetSocket = new File("/tmp/datagram-receiver.sock");
try (AFUNIXDatagramSocket sender = AFUNIXDatagramSocket.newInstance()) {
    String message = "Hello via datagram";
    byte[] data = message.getBytes(StandardCharsets.UTF_8);
    
    DatagramPacket packet = new DatagramPacket(
        data, data.length, AFUNIXSocketAddress.of(targetSocket)
    );
    
    sender.send(packet);
}

// Datagram receiver
File receiverSocket = new File("/tmp/datagram-receiver.sock");
try (AFUNIXDatagramSocket receiver = AFUNIXDatagramSocket.bindOn(AFUNIXSocketAddress.of(receiverSocket))) {
    
    byte[] buffer = new byte[1024];
    DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
    
    receiver.receive(packet);
    
    String receivedMessage = new String(packet.getData(), 0, packet.getLength(), StandardCharsets.UTF_8);
    System.out.println("Received: " + receivedMessage);
    System.out.println("From: " + packet.getSocketAddress());
}

Socket Configuration

Connection Options

// Socket timeout configuration
public void setSoTimeout(int timeout) throws SocketException;
public int getSoTimeout() throws SocketException;

// Keep-alive configuration  
public void setKeepAlive(boolean on) throws SocketException;
public boolean getKeepAlive() throws SocketException;

// Buffer size configuration
public void setReceiveBufferSize(int size) throws SocketException;
public int getReceiveBufferSize() throws SocketException;
public void setSendBufferSize(int size) throws SocketException;
public int getSendBufferSize() throws SocketException;

Advanced Features

// Connection validation
public boolean checkConnectionClosed() throws IOException;

// File descriptor access
public FileDescriptor getFileDescriptor() throws IOException;

// Peer credentials (Linux/macOS)
public PeerCredentials getPeerCredentials() throws IOException;

Error Handling

Common exceptions when working with Unix Domain Sockets:

// Socket-specific exceptions
public class AFException extends IOException;
public class SocketClosedException extends SocketException;
public class AddressUnavailableSocketException extends SocketException;
public class BrokenPipeSocketException extends SocketException;
public class ConnectionResetSocketException extends SocketException;

Error Handling Examples:

try {
    AFUNIXSocket socket = AFUNIXSocket.connectTo(AFUNIXSocketAddress.of(socketFile));
    // Use socket...
} catch (AddressUnavailableSocketException e) {
    System.err.println("Socket file does not exist or server not running");
} catch (ConnectionResetSocketException e) {
    System.err.println("Connection was reset by peer");
} catch (BrokenPipeSocketException e) {
    System.err.println("Broken pipe - peer closed connection");
} catch (SocketClosedException e) {
    System.err.println("Attempted operation on closed socket");
} catch (IOException e) {
    System.err.println("General I/O error: " + e.getMessage());
}

Install with Tessl CLI

npx tessl i tessl/maven-com-kohlschutter-junixsocket--junixsocket-core

docs

addressing.md

capabilities.md

datagram-sockets.md

exceptions.md

file-descriptors.md

index.md

nio-channels.md

rmi.md

socket-pairs.md

unix-sockets.md

utilities.md

tile.json