started migration to ktor sockets (e.g. tcp on all platforms but JS)

This commit is contained in:
sergeych committed 2024-08-02 02:47:26 +02:00
1 parent 326b92142d
commit 26d1f3522f
4 files changed
+175 -108

No files matched your search

@@ -1,49 +1,39 @@
package net.sergeych.kiloparsec.adapter
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import java.net.InetAddress
import java.net.InetSocketAddress
import java.nio.channels.AsynchronousServerSocketChannel
import java.nio.channels.AsynchronousSocketChannel
import kotlin.coroutines.suspendCoroutine
actual fun NetworkAddress(host: String, port: Int): NetworkAddress =
JvmNetworkAddress(InetAddress.getByName(host), port)
actual fun acceptTcpDevice(port: Int): Flow<InetTransportDevice> {
return flow {
val socket = withContext(Dispatchers.IO) {
AsynchronousServerSocketChannel.open().also {
it.bind(InetSocketAddress(port))
}
}
while (true) {
println("0 --- $port")
val connectedSocket = suspendCancellableCoroutine { continuation ->
continuation.invokeOnCancellation {
socket.close()
}
socket.accept(continuation, ContinuationHandler())
}
println("1 ---")
emit(asyncSocketToDevice(connectedSocket))
}
}
}
@Suppress("unused")
suspend fun connectTcpDevice(host: String, port: Int) = connectTcpDevice(NetworkAddress(host,port))
actual suspend fun connectTcpDevice(address: NetworkAddress): InetTransportDevice {
address as JvmNetworkAddress
val socket = withContext(Dispatchers.IO) {
AsynchronousSocketChannel.open()
}
suspendCoroutine { cont ->
socket.connect(address.socketAddress, cont, VoidCompletionHandler)
}
return asyncSocketToDevice(socket)
}
//
//actual fun NetworkAddress(host: String, port: Int): NetworkAddress =
// JvmNetworkAddress(InetAddress.getByName(host), port)
//
//actual fun acceptTcpDevice(port: Int): Flow<InetTransportDevice> {
// return flow {
// val socket = withContext(Dispatchers.IO) {
// AsynchronousServerSocketChannel.open().also {
// it.bind(InetSocketAddress(port))
// }
// }
// while (true) {
// println("0 --- $port")
// val connectedSocket = suspendCancellableCoroutine { continuation ->
// continuation.invokeOnCancellation {
// socket.close()
// }
// socket.accept(continuation, ContinuationHandler())
// }
// println("1 ---")
// emit(asyncSocketToDevice(connectedSocket))
// }
// }
//}
//
//@Suppress("unused")
//suspend fun connectTcpDevice(host: String, port: Int) = connectTcpDevice(NetworkAddress(host,port))
//actual suspend fun connectTcpDevice(address: NetworkAddress): InetTransportDevice {
// address as JvmNetworkAddress
// val socket = withContext(Dispatchers.IO) {
// AsynchronousSocketChannel.open()
// }
// suspendCoroutine { cont ->
// socket.connect(address.socketAddress, cont, VoidCompletionHandler)
// }
// return asyncSocketToDevice(socket)
//}