idiomatic-kotlin-course/src/main/kotlin/streamingModule.kt

40 lines
987 B
Kotlin

import io.ktor.server.routing.Route
import io.ktor.server.routing.application
import io.ktor.server.websocket.webSocket
import io.ktor.websocket.Frame
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import java.time.Instant
import kotlin.time.Duration.Companion.microseconds
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
fun Route.streamingModule() {
val channel = Channel<Instant>()
application.launch {
while (isActive) {
delay(0.1.seconds)
channel.send(Instant.now())
}
}
webSocket {
repeat(3){
delay(100.milliseconds)
outgoing.send(Frame.Text(Instant.now().toString()))
}
// launch {
// while (isActive) {
// outgoing.send(Frame.Text(channel.receive().toString()))
// }
// }
}
}