When working with sockets. Is there a way to react...
# ktor
c
When working with sockets. Is there a way to reactively know when there's a disconnection without polling? Or I'll have to poll?
a
Here is a point, relevant to Ktor sockets, from the answer on StackOverflow about Java sockets:
The only really reliable way to detect a lost TCP connection is to write to it. Eventually this will throw an
IOException: connection reset
, but it takes at least two writes due to buffering.
Here is an example of how to detect the disconnection:
Copy code
val selectorManager = SelectorManager(<http://Dispatchers.IO|Dispatchers.IO>)
val socket = aSocket(selectorManager).tcp().connect("127.0.0.1", 12345)

socket.openWriteChannel(autoFlush = true).use {
    while (true) {
        try {
            writeStringUtf8("Hello, world!\n")
        } catch (_: ClosedWriteChannelException) {
            println("Disconnected")
            break
        }
        delay(500)
    }
}
👍 1