TCP sockets
suggest changeTCP gives you a reliable, ordered, two-way stream of bytes between two programs. HTTP, WebSockets, database protocols, SMTP and Redis all run on top of it. You usually use a higher-level library (see HTTP client and WebSockets), but sometimes you have to speak a custom protocol or talk to a device. Then you work with sockets directly.
Kotlin on the JVM gives you two main options:
java.net.Socketandjava.net.ServerSocketfrom the JDK. They use blocking I/O and need no dependencies. Since Java 21, virtual threads make blocking servers cheap.- Ktor's
ktor-network, a coroutine-based socket API whereaccept(), reads and writes are suspend functions.
All examples below were compiled with Kotlin 2.4.21 on JDK 25. The Ktor example uses Ktor 3.6.0.
Echo server and client
A server creates a ServerSocket bound to a port and calls accept(). That call blocks until a client connects, then returns a Socket for that one connection. A client creates a Socket(host, port), which connects right away.
Each Socket has an InputStream and an OutputStream. Wrap them in a reader and a writer to work with lines of text:
import java.net.ServerSocket
import java.net.Socket
import kotlin.concurrent.thread
fun main() {
val server = ServerSocket(0) // 0 = let the OS pick a free port
val port = server.localPort
val serverThread = thread {
server.use { ss ->
ss.accept().use { conn ->
println("server: connection from ${conn.inetAddress.hostAddress}")
val reader = conn.getInputStream().bufferedReader()
val writer = conn.getOutputStream().bufferedWriter()
while (true) {
val line = reader.readLine() ?: break // null = client closed
writer.write("echo: $line\n")
writer.flush()
}
println("server: client disconnected")
}
}
}
Socket("localhost", port).use { socket ->
val reader = socket.getInputStream().bufferedReader()
val writer = socket.getOutputStream().bufferedWriter()
for (msg in listOf("hello", "tcp")) {
writer.write("$msg\n")
writer.flush()
println("client: ${reader.readLine()}")
}
}
serverThread.join()
}
Output:
server: connection from 127.0.0.1
client: echo: hello
client: echo: tcp
server: client disconnected
Things to notice:
SocketandServerSocketimplementCloseable, souse { }closes them even when an exception is thrown (see use and Closeable).- Always
flush()a buffered writer. If you forget, the data stays in the buffer, and both sides wait for each other forever. readLine()returnsnullwhen the other side closes the connection. This "end of stream" is how you know a peer is gone.- Port
0asks the OS for any free port. Read the real port fromlocalPort. This is handy in tests. bufferedReader()andbufferedWriter()use UTF-8 by default. Both sides must agree on the encoding.
Serving many clients with virtual threads
The server above handles a single connection. A real server runs accept() in a loop and hands each connection to its own thread. Platform threads are expensive, so older code used a fixed thread pool. With virtual threads you can create one thread per connection, even for tens of thousands of connections:
import java.net.ServerSocket
import java.net.Socket
import java.net.SocketException
import java.util.concurrent.Executors
import kotlin.concurrent.thread
fun handle(conn: Socket) {
conn.use {
val reader = it.getInputStream().bufferedReader()
val writer = it.getOutputStream().bufferedWriter()
val name = reader.readLine() ?: return
Thread.sleep(200) // pretend to do slow work
writer.write("hello, $name (virtual thread: ${Thread.currentThread().isVirtual})\n")
writer.flush()
}
}
fun main() {
val server = ServerSocket(0)
val acceptor = thread {
Executors.newVirtualThreadPerTaskExecutor().use { pool ->
try {
while (true) {
val conn = server.accept()
pool.submit { handle(conn) }
}
} catch (e: SocketException) {
println("server stopped: ${e.message}")
}
}
}
val start = System.nanoTime()
val clients = (1..5).map { i ->
thread {
Socket("localhost", server.localPort).use { s ->
val w = s.getOutputStream().bufferedWriter()
w.write("client-$i\n")
w.flush()
val reply = s.getInputStream().bufferedReader().readLine()
synchronized(System.out) { println(reply) }
}
}
}
clients.forEach { it.join() }
val ms = (System.nanoTime() - start) / 1_000_000
println("5 clients served in under 1 second: ${ms < 1000}")
server.close() // makes accept() throw SocketException
acceptor.join()
}
Output (the order of the first five lines varies between runs):
hello, client-5 (virtual thread: true)
hello, client-2 (virtual thread: true)
hello, client-1 (virtual thread: true)
hello, client-4 (virtual thread: true)
hello, client-3 (virtual thread: true)
5 clients served in under 1 second: true
server stopped: Socket closed
Each handler sleeps for 200 ms, but the clients are served concurrently, so all five finish in about 200 ms, not one second.
To stop a server that is blocked in accept(), close the ServerSocket from another thread. accept() then throws a SocketException, which ends the loop. Combine this with a shutdown hook to stop cleanly on Ctrl+C (see Signals and graceful shutdown).
TCP is a stream, not messages
This is the most common source of socket bugs. TCP does not keep message boundaries. If the client makes two write() calls, the server might receive both in one read(). A single write can also arrive split across several reads. A plain InputStream.read(buffer) returns whatever bytes have arrived so far.
So your protocol needs framing, a way to tell where one message ends and the next starts. There are two common approaches:
- Delimiters, such as one message per line. That's what
readLine()gave us above. It is simple and readable, but the message must not contain the delimiter. - Length prefix: send the size of the message first, then its bytes. This works for any data, binary included.
DataOutputStream and DataInputStream make length-prefixed framing easy. readFully() keeps reading until the whole buffer is filled:
import java.io.DataInputStream
import java.io.DataOutputStream
import java.io.EOFException
import java.net.ServerSocket
import java.net.Socket
import kotlin.concurrent.thread
// Each message: 4-byte big-endian length, then that many bytes of UTF-8
fun DataOutputStream.writeMessage(text: String) {
val bytes = text.encodeToByteArray()
writeInt(bytes.size)
write(bytes)
}
fun DataInputStream.readMessage(maxSize: Int = 1 shl 20): String? {
val size = try {
readInt()
} catch (e: EOFException) {
return null // clean end of stream between messages
}
require(size in 0..maxSize) { "bad message size $size" }
val bytes = ByteArray(size)
readFully(bytes) // keeps reading until all bytes have arrived
return bytes.decodeToString()
}
fun main() {
val server = ServerSocket(0)
val t = thread {
server.use { it.accept() }.use { conn ->
val input = DataInputStream(conn.getInputStream().buffered())
while (true) {
val msg = input.readMessage() ?: break
println("server got ${msg.length} chars: ${msg.take(16).replace("\n", "|")}")
}
}
}
Socket("localhost", server.localPort).use { s ->
val out = DataOutputStream(s.getOutputStream().buffered())
out.writeMessage("short")
out.writeMessage("multi\nline\nmessage")
out.writeMessage("x".repeat(100_000))
out.writeMessage("")
out.flush()
}
t.join()
}
Output:
server got 5 chars: short
server got 18 chars: multi|line|messa
server got 100000 chars: xxxxxxxxxxxxxxxx
server got 0 chars:
The 100,000-byte message almost certainly arrived in several TCP segments, but readFully puts it back together. Always check the length against a maximum before you allocate the buffer. Otherwise a broken or malicious peer can send 0x7FFFFFFF and make you allocate 2 GB. For more on encoding integers into bytes, see Bytes and binary data.
Half-close: signalling the end of a request
Sometimes the request is "everything until the end of the stream", for example when you upload a file. The client can't close the socket to signal the end, because then it couldn't read the reply. Instead it calls shutdownOutput(). This sends a FIN to the peer, whose reads then see end of stream. The client can still read from its side of the connection:
import java.net.ServerSocket
import java.net.Socket
import kotlin.concurrent.thread
fun main() {
val server = ServerSocket(0)
val t = thread {
server.use { it.accept() }.use { conn ->
// read everything until the client shuts down its output
val request = conn.getInputStream().readAllBytes().decodeToString()
val words = request.split(Regex("\\s+")).filter { it.isNotEmpty() }
val reply = "${words.size} words, ${request.length} chars"
conn.getOutputStream().write(reply.encodeToByteArray())
}
}
Socket("localhost", server.localPort).use { s ->
val text = "the quick brown fox\njumps over the lazy dog\n"
s.getOutputStream().write(text.encodeToByteArray())
s.shutdownOutput() // sends FIN: no more writes, but we can still read
println("output shut down: ${s.isOutputShutdown}, closed: ${s.isClosed}")
val reply = s.getInputStream().readAllBytes().decodeToString()
println("reply: $reply")
}
t.join()
}
Output:
output shut down: true, closed: false
reply: 9 words, 44 chars
Be careful with streams you get from a socket. Closing socket.getInputStream() or socket.getOutputStream(), or a reader or writer that wraps them, closes the whole socket. Use shutdownInput() and shutdownOutput() to close just one direction.
Errors and timeouts
By default, connects and reads can block forever. Production code should always set timeouts:
- Connect timeout: create an unconnected
Socket()and callconnect(address, timeoutMs). TheSocket(host, port)constructor uses the OS default, which can be minutes. - Read timeout:
soTimeout(in ms) limits how long eachread()waits. When it runs out you get aSocketTimeoutException, but the socket stays open and you can retry.
import java.net.ConnectException
import java.net.InetSocketAddress
import java.net.ServerSocket
import java.net.Socket
import java.net.SocketTimeoutException
import java.net.UnknownHostException
fun main() {
// 1. Nobody listening on the port
val freePort = ServerSocket(0).use { it.localPort }
try {
Socket().use { it.connect(InetSocketAddress("127.0.0.1", freePort), 3000) }
} catch (e: ConnectException) {
println("ConnectException: ${e.message}")
}
// 2. Host name that doesn't resolve
try {
Socket("no-such-host.invalid", 80).close()
} catch (e: UnknownHostException) {
println("UnknownHostException: ${e.message}")
}
// 3. Server accepts but never answers: read timeout
ServerSocket(0).use { silent ->
Socket().use { s ->
s.connect(InetSocketAddress("127.0.0.1", silent.localPort), 3000)
s.soTimeout = 500 // ms; applies to every read()
val start = System.nanoTime()
try {
s.getInputStream().read()
} catch (e: SocketTimeoutException) {
val ms = (System.nanoTime() - start) / 1_000_000
println("SocketTimeoutException: ${e.message} after ~${ms / 100 * 100} ms")
}
println("socket still open: ${!s.isClosed}")
}
}
}
Output (on Windows; on Linux the first message is just Connection refused):
ConnectException: Connection refused: getsockopt
UnknownHostException: no-such-host.invalid
SocketTimeoutException: Read timed out after ~500 ms
socket still open: true
In case 3 the connection succeeds even though the server never calls accept(). The OS completes the TCP handshake and puts the connection in the listen backlog. A successful connect only tells you the port is open. It doesn't tell you the application is responding.
Other exceptions you will see:
| Exception | Typical cause |
|---|---|
ConnectException: Connection refused |
Nothing is listening on that host and port |
SocketTimeoutException: Connect timed out |
Host unreachable or a firewall drops packets |
SocketException: Connection reset |
The peer closed abruptly or crashed (it sent an RST) |
SocketException: Broken pipe / Connection reset by peer |
You wrote to a connection the peer already closed |
BindException: Address already in use |
Another process (or your previous run) holds the port |
All of them extend IOException, so a single catch (e: IOException) around the per-connection code keeps one bad client from killing your server.
Socket options
import java.net.InetSocketAddress
import java.net.ServerSocket
import java.net.Socket
fun main() {
ServerSocket().use { server ->
server.reuseAddress = true // allow a quick restart on the same port
server.bind(InetSocketAddress("127.0.0.1", 0), 100) // backlog: 100 pending connections
Socket().use { s ->
s.tcpNoDelay = true // disable Nagle's algorithm: send small writes immediately
s.keepAlive = true // OS sends keep-alive probes on idle connections
s.soTimeout = 10_000 // read timeout in ms (0 = wait forever)
s.connect(server.localSocketAddress, 2_000) // connect timeout in ms
server.accept().use { peer ->
println("tcpNoDelay=${s.tcpNoDelay} keepAlive=${s.keepAlive} soTimeout=${s.soTimeout}")
println("receive buffer > 0: ${s.receiveBufferSize > 0}")
println("client port seen by server matches: ${s.localPort == peer.port}")
println("remote: ${s.remoteSocketAddress.toString().substringBeforeLast(':')}")
}
}
}
}
Output:
tcpNoDelay=true keepAlive=true soTimeout=10000
receive buffer > 0: true
client port seen by server matches: true
remote: /127.0.0.1
tcpNoDelay: by default TCP holds back small writes so it can combine them into fewer packets (Nagle's algorithm). This adds latency to request/response protocols that send small messages, so interactive protocols usually turn it on. Buffering your own writes and flushing once per message also helps.keepAlive: detects dead peers on idle connections. The OS default interval is often 2 hours, so many protocols send their own heartbeat messages instead.reuseAddress: lets a restarted server bind to a port that still has connections inTIME_WAIT. You must set it beforebind().- Bind address:
127.0.0.1accepts connections only from the same machine.0.0.0.0(the default forServerSocket(port)) accepts connections on every network interface.
Coroutine sockets with Ktor
In coroutine code you have two choices. You can wrap blocking socket calls in withContext(Dispatchers.IO) { ... }. Or you can use ktor-network, where accept, connect and every read and write suspend instead of blocking a thread. Add the dependency:
dependencies {
implementation("io.ktor:ktor-network:3.6.0")
}
The server below upper-cases every line it receives and runs one coroutine per connection. Three clients connect concurrently:
import io.ktor.network.selector.SelectorManager
import io.ktor.network.sockets.InetSocketAddress
import io.ktor.network.sockets.aSocket
import io.ktor.network.sockets.openReadChannel
import io.ktor.network.sockets.openWriteChannel
import io.ktor.utils.io.readLine
import io.ktor.utils.io.writeStringUtf8
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val selector = SelectorManager(Dispatchers.IO)
val server = aSocket(selector).tcp().bind("127.0.0.1", 0)
val port = (server.localAddress as InetSocketAddress).port
val serverJob = launch {
while (true) {
val socket = server.accept() // suspends, doesn't block a thread
launch { // one coroutine per connection
socket.use {
val input = it.openReadChannel()
val output = it.openWriteChannel(autoFlush = true)
while (true) {
val line = input.readLine() ?: break
output.writeStringUtf8("${line.uppercase()}\n")
}
}
}
}
}
coroutineScope {
for (i in 1..3) {
launch {
aSocket(selector).tcp().connect("127.0.0.1", port).use { socket ->
val input = socket.openReadChannel()
val output = socket.openWriteChannel(autoFlush = true)
output.writeStringUtf8("message from client $i\n")
println(input.readLine())
}
}
}
}
serverJob.cancel()
server.close()
selector.close()
}
Output:
MESSAGE FROM CLIENT 1
MESSAGE FROM CLIENT 2
MESSAGE FROM CLIENT 3
Notes:
SelectorManagerowns the NIO selector that drives all sockets. Create one, share it, and close it when you're done.openReadChannel()returns aByteReadChannel. BesidesreadLine(), it hasreadInt(),readFully()andreadByteArray(n)for binary protocols. In Ktor 3,readLine()replaces the deprecatedreadUTF8Line().- Without
autoFlush = trueyou must calloutput.flush()after writing, just like with a buffered writer. - Cancelling the coroutine cancels a suspended
accept()or read. That makes timeouts as simple aswithTimeout(5.seconds) { input.readLine() }(see Cancellation and timeouts). - For TLS, call
socket.tls(coroutineContext)fromktor-network-tls. On the JDK side useSSLSocketFactory. See TLS and HTTPS.
Checklist
- Define framing: lines or a length prefix. Never assume one
read()equals one message. - Flush after each message, or use
autoFlush. - Set a connect timeout and a read timeout.
- Close sockets with
use { }. Closing a socket's stream closes the socket. - Catch
IOExceptionper connection so one client can't crash the server. - Limit message sizes before you allocate memory.
- Use virtual threads (blocking API) or coroutines (Ktor) to serve many clients at once.