I am working on a KMP Mobile app that sends data t...
# ktor
f
I am working on a KMP Mobile app that sends data to desktop over sockets. I have trouble closing ktor's
aSocket
. To close Socket I use
disconnect()
. However when I try to connect to the same IP and Port I get
java.net.BindException: Address already in use
. I also noticed that
socket?.dispose()
takes infinite time to complete. How can I close
aSocket
for this to work properly?
Copy code
private val selectorManager = SelectorManager(Dispatchers.IO)
private var socket: Socket? = null
private var writeChannel: ByteWriteChannel? = null
private var readChannel: ByteReadChannel? = null

suspend fun connect(ip: String, port: Int) {
    socket = aSocket(selectorManager)
        .tcp()
        .bind(ip, port)
        .accept()
}

override suspend fun disconnect() {
    withContext(Dispatchers.IO) {
        writeChannel?.close()
        readChannel = null
        socket?.dispose()
    }
}
a
I cannot find the
disconnect
method but only the
close
and
cancel
methods which you can try. You can try using the SO_REUSEADDR TCP/IP socket option to solve your problem.