CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-io-ktor--ktor-network-macosarm64

Ktor network utilities for macOS ARM64 target - provides asynchronous networking components including sockets, selectors, and connection utilities for building Kotlin multiplatform network applications

Pending
Overview
Eval results
Files

socket-options.mddocs/

Socket Options

Ktor Network provides a comprehensive socket configuration system through typed options classes. The options system allows fine-tuning of socket behavior, performance characteristics, and network properties.

Base Options Classes

Socket Options Hierarchy

sealed class SocketOptions

class SocketOptions.PeerSocketOptions : SocketOptions() {
    var sendBufferSize: Int? = null
    var receiveBufferSize: Int? = null
    var reuseAddress: Boolean = true
    var reusePort: Boolean = false
}

Base options class providing buffer size and address reuse settings for peer connections.

Properties:

  • sendBufferSize: Int? - Send buffer size in bytes (null = system default)
  • receiveBufferSize: Int? - Receive buffer size in bytes (null = system default)
  • reuseAddress: Boolean - Allow address reuse (default: false)
  • reusePort: Boolean - Allow port reuse (default: false)

TCP Socket Options

TCP Client Options

class SocketOptions.TCPClientSocketOptions : SocketOptions.PeerSocketOptions() {
    var keepAlive: Boolean? = null
    var noDelay: Boolean = true
    var lingerSeconds: Int = -1
    var socketTimeout: Long = INFINITE_TIMEOUT_MS
}

TCP-specific options for client connections and general TCP behavior.

Properties:

  • keepAlive: Boolean? - Enable TCP keepalive probes (null = system default)
  • noDelay: Boolean - Disable Nagle's algorithm for lower latency (default: true)
  • lingerSeconds: Int - Linger time in seconds on close (-1 = system default, not set)
  • socketTimeout: Long - Socket timeout in milliseconds (default: INFINITE_TIMEOUT_MS)

UDP Socket Options

UDP Options

class SocketOptions.UDPSocketOptions : SocketOptions.PeerSocketOptions() {
    var broadcast: Boolean? = null
}

UDP-specific options for datagram communication.

Properties:

  • broadcast: Boolean? - Enable broadcast packet transmission (null = system default)

Server Socket Options

Acceptor Options

class SocketOptions.AcceptorOptions : SocketOptions() {
    var backlogSize: Int = 511
    var reuseAddress: Boolean = true
    var reusePort: Boolean = false
}

Options specific to server sockets that accept connections.

Properties:

  • backlogSize: Int - Maximum pending connection queue size (default: 511)
  • reuseAddress: Boolean - Allow address reuse (default: true)
  • reusePort: Boolean - Allow multiple sockets to bind to same port (default: false)

Configuration Interface

Configurable Interface

interface Configurable<out T : Configurable<T, Options>, Options : SocketOptions> {
    fun configure(block: Options.() -> Unit): T
}

Interface enabling fluent configuration of socket builders with type-safe options.

Usage Examples

TCP Client Configuration

import io.ktor.network.sockets.*
import io.ktor.network.selector.*

suspend fun createOptimizedTcpClient() {
    val selectorManager = SelectorManager()
    
    val socket = aSocket(selectorManager)
        .tcp()
        .configure {
            // Performance optimizations
            noDelay = true                    // Disable Nagle's algorithm
            keepAlive = true                  // Enable keepalive
            socketTimeout = 30000             // 30 second timeout
            
            // Buffer sizing
            sendBufferSize = 64 * 1024        // 64KB send buffer
            receiveBufferSize = 64 * 1024     // 64KB receive buffer
            
            // Address reuse
            reuseAddress = true
            reusePort = false
            
            // Connection cleanup
            lingerSeconds = 0                 // Close immediately
        }
        .connect(InetSocketAddress("api.example.com", 443))
    
    println("Optimized TCP connection established")
    socket.close()
    selectorManager.close()
}

TCP Server Configuration

suspend fun createHighPerformanceServer() {
    val selectorManager = SelectorManager()
    
    val serverSocket = aSocket(selectorManager)
        .tcp()
        .configure {
            // Server-specific options  
            backlogSize = 1000               // Large connection queue
            reuseAddress = true              // Allow quick restart
            reusePort = true                 // Allow load balancing
            
            // Buffer optimization
            sendBufferSize = 128 * 1024      // 128KB send buffer
            receiveBufferSize = 128 * 1024   // 128KB receive buffer
        }
        .bind(InetSocketAddress("0.0.0.0", 8080))
    
    println("High-performance server listening on ${serverSocket.localAddress}")
    
    // Accept connections with client-specific options
    while (!serverSocket.isClosed) {
        val clientSocket = serverSocket.accept()
        
        // Client connection inherits server buffer settings
        println("Client connected: ${clientSocket.remoteAddress}")
        
        // Handle client in coroutine
        launch {
            handleClient(clientSocket)
        }
    }
    
    serverSocket.close()
    selectorManager.close()
}

suspend fun handleClient(client: Socket) {
    // Client handling logic
    client.close()
}

UDP Socket Configuration

suspend fun createBroadcastUdpSocket() {
    val selectorManager = SelectorManager()
    
    val socket = aSocket(selectorManager)
        .udp()
        .configure {
            // Enable broadcast transmission
            broadcast = true
            
            // Larger buffers for bulk data
            sendBufferSize = 256 * 1024      // 256KB for large datagrams
            receiveBufferSize = 256 * 1024
            
            // Address reuse for multi-instance deployment
            reuseAddress = true
            reusePort = true
        }
        .bind(InetSocketAddress("0.0.0.0", 9999))
    
    // Can now send broadcast packets
    val broadcastDatagram = Datagram(
        packet = ByteReadPacket("Broadcast message".toByteArray()),
        address = InetSocketAddress("255.255.255.255", 9999)
    )
    
    socket.send(broadcastDatagram)
    println("Broadcast sent")
    
    socket.close()
    selectorManager.close()
}

Performance Tuning Examples

suspend fun createLowLatencyConnection() {
    val selectorManager = SelectorManager()
    
    // Low-latency configuration
    val socket = aSocket(selectorManager)
        .tcp()
        .configure {
            noDelay = true                   // Immediate transmission
            keepAlive = false                // Reduce overhead
            lingerSeconds = 0                // Fast close
            socketTimeout = 5000             // Quick timeout
            
            // Smaller buffers for lower latency
            sendBufferSize = 8 * 1024        // 8KB
            receiveBufferSize = 8 * 1024     // 8KB
        }
        .connect(InetSocketAddress("low-latency-service.com", 7777))
    
    println("Low-latency connection established")
    socket.close()
    selectorManager.close()
}

suspend fun createHighThroughputConnection() {
    val selectorManager = SelectorManager()
    
    // High-throughput configuration
    val socket = aSocket(selectorManager)
        .tcp()
        .configure {
            noDelay = false                  // Allow batching (Nagle's algorithm)
            keepAlive = true                 // Keep connections alive
            socketTimeout = 300000           // Long timeout (5 minutes)
            
            // Large buffers for bulk transfer
            sendBufferSize = 1024 * 1024     // 1MB
            receiveBufferSize = 1024 * 1024  // 1MB
            
            lingerSeconds = 30               // Graceful close
        }
        .connect(InetSocketAddress("bulk-transfer.com", 8888))
    
    println("High-throughput connection established")
    socket.close()
    selectorManager.close()
}

Platform-Specific Configuration

suspend fun createMacOSOptimizedSocket() {
    val selectorManager = SelectorManager()
    
    val socket = aSocket(selectorManager)
        .tcp()
        .configure {
            // macOS-specific optimizations
            keepAlive = true
            noDelay = true
            
            // Optimal buffer sizes for macOS ARM64
            sendBufferSize = 256 * 1024      // 256KB
            receiveBufferSize = 256 * 1024
            
            // Port reuse for development
            reuseAddress = true
            reusePort = true
            
            // Reasonable timeout
            socketTimeout = 60000            // 1 minute
        }
        .connect(InetSocketAddress("localhost", 8080))
    
    println("macOS optimized connection")
    socket.close()
    selectorManager.close()
}

Configuration Patterns

// Define reusable configuration functions
fun SocketOptions.TCPClientSocketOptions.applyWebClientDefaults() {
    keepAlive = true
    noDelay = true
    socketTimeout = 30000
    sendBufferSize = 32 * 1024
    receiveBufferSize = 32 * 1024
    reuseAddress = true
}

fun SocketOptions.TCPClientSocketOptions.applyGameClientDefaults() {
    keepAlive = true
    noDelay = true                          // Low latency priority
    socketTimeout = 5000                    // Quick timeout
    sendBufferSize = 16 * 1024             // Smaller buffers
    receiveBufferSize = 16 * 1024
    lingerSeconds = 0                       // Fast close
}

fun SocketOptions.AcceptorOptions.applyWebServerDefaults() {
    backlogSize = 1000
    reuseAddress = true
    reusePort = false
}

suspend fun useConfigurationPatterns() {
    val selectorManager = SelectorManager()
    
    // Web client with defaults
    val webClient = aSocket(selectorManager)
        .tcp()
        .configure { applyWebClientDefaults() }
        .connect(InetSocketAddress("api.example.com", 80))
    
    // Game client with low-latency defaults  
    val gameClient = aSocket(selectorManager)
        .tcp()
        .configure { applyGameClientDefaults() }
        .connect(InetSocketAddress("game-server.com", 7777))
    
    // Web server with defaults
    val webServer = aSocket(selectorManager)
        .tcp()
        .configure { applyWebServerDefaults() }
        .bind(InetSocketAddress("0.0.0.0", 8080))
    
    // Clean up
    webClient.close()
    gameClient.close()  
    webServer.close()
    selectorManager.close()
}

Option Value Guidelines

Buffer Sizes

  • Small buffers (4-16KB): Low-latency applications, real-time communication
  • Medium buffers (32-64KB): General purpose applications, web services
  • Large buffers (128KB-1MB): Bulk data transfer, file streaming

Timeouts

  • Short timeouts (1-5 seconds): Interactive applications, real-time services
  • Medium timeouts (30-60 seconds): Web applications, API clients
  • Long timeouts (5+ minutes): Bulk operations, file transfers

TCP Options

  • noDelay = true: Low-latency priority (gaming, real-time)
  • noDelay = false: Throughput priority (bulk transfer)
  • keepAlive = true: Long-lived connections
  • keepAlive = false: Short-lived connections

Type Definitions

Required Import Statements

import io.ktor.network.sockets.*

Related Types

  • Configuration is used with builders - See Socket Builders
  • Options affect all socket types - See Socket Interfaces
  • UDP options are specific - See Datagram Sockets

Install with Tessl CLI

npx tessl i tessl/maven-io-ktor--ktor-network-macosarm64

docs

address-types.md

datagram-sockets.md

index.md

selectors.md

socket-builders.md

socket-interfaces.md

socket-options.md

utilities.md

tile.json