commonMain.com.apadmi.mockzilla.lib.internal.utils.SocketIo.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of mockzilla-jvm Show documentation
Show all versions of mockzilla-jvm Show documentation
Solution for running and configuring a local HTTP server on mobile.
The newest version!
package com.apadmi.mockzilla.lib.internal.utils
import io.ktor.network.selector.SelectorManager
import io.ktor.network.sockets.ServerSocket
import io.ktor.network.sockets.aSocket
internal interface SocketBinder {
suspend fun bind(hostname: String, port: Int): ServerSocket
}
internal class SocketBinderImpl(private val selectorManager: SelectorManager) : SocketBinder {
override suspend fun bind(hostname: String, port: Int): ServerSocket =
aSocket(selectorManager).tcp().bind(hostname, port)
}
internal class SocketIo(private val socketBinder: SocketBinder) {
/**
* Ktor treats port `0` as a flag to use a random, available port. See more at
* https://ktor.io/docs/server-configuration-code.html#embedded-basic
*/
private val Int.isRandomPortFlag: Boolean
get() = this == 0
suspend fun isPortAvailable(port: Int): Boolean = port.isRandomPortFlag || runCatching {
val serverSocket = socketBinder.bind("127.0.0.1", port)
serverSocket.dispose()
}.isSuccess
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy