Skip to main content

Socket

Cross-platform TCP + TLS with streaming, compression, and buffer pooling — same Kotlin code on 6 platforms

Socket provides suspend-based async socket I/O with platform-native implementations, allowing you to write networking code once and run it across JVM, Android, iOS, macOS, Linux, and Node.js.

Why Socket?

  • One-line TLSSocketOptions.tlsDefault() handles SSLEngine, Network.framework, OpenSSL, and Node tls module
  • StreamingreadFlowLines() with backpressure, cancellation, and constant memory
  • Buffer poolingSocketConnection bundles pool + stream processor, no per-message allocations
  • Compression — compose mapBuffer { decompress(it) } into any read pipeline
  • Lambda-scoped connections — auto-cleanup, no try-finally
  • Platform-native performance — io_uring on Linux, NWConnection on Apple, NIO2 on JVM

Platform Implementations

PlatformNative TypeNotes
JVMAsynchronousSocketChannelNIO2 with NIO fallback
AndroidSame as JVMShared commonJvmMain source set
iOS/macOS/tvOS/watchOSNWConnectionNetwork.framework, zero-copy
Linux (x64/arm64)io_uringKernel 5.1+, zero-copy, static OpenSSL
Node.jsnet.SocketNode.js networking API

Quick Example

Request/Response

val response = ClientSocket.connect(443, hostname = "example.com", socketOptions = SocketOptions.tlsDefault()) { socket ->
socket.writeString("GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n")
socket.readString()
} // socket closed automatically

Persistent Streaming

ClientSocket.connect(8883, hostname = "broker.example.com", socketOptions = SocketOptions.tlsDefault()) { socket ->
socket.writeString("SUBSCRIBE events\n")
socket.readFlowLines().collect { line ->
println(line)
}
}

Streaming with Compression

socket.readFlow()
.mapBuffer { decompress(it, Gzip).getOrThrow() }
.asStringFlow()
.lines()
.collect { line -> process(line) }

Part of the DitchOoM Stack

┌──────────────────────────────────┐
│ Your Protocol (MQTT, WS, ...) │
├──────────────────────────────────┤
│ socket (TCP + TLS) │ ← com.ditchoom:socket
├──────────────────────────────────┤
│ buffer-compression (optional) │ ← com.ditchoom:buffer-compression
├──────────────────────────────────┤
│ buffer-flow │ ← com.ditchoom:buffer-flow
├──────────────────────────────────┤
│ buffer │ ← com.ditchoom:buffer
└──────────────────────────────────┘

Installation

Add to your build.gradle.kts (see Maven Central for latest versions):

dependencies {
implementation("com.ditchoom:socket:<latest-version>")
// Optional: streaming transforms (mapBuffer, asStringFlow, lines)
implementation("com.ditchoom:buffer-flow:<latest-version>")
// Optional: compression
implementation("com.ditchoom:buffer-compression:<latest-version>")
}

Next Steps