portal/src/jvmMain/kotlin/de/kif/backend/route/PushService.kt
2019-05-10 11:59:41 +02:00

47 lines
No EOL
1.3 KiB
Kotlin

package de.kif.backend.route
import io.ktor.http.cio.websocket.Frame
import io.ktor.http.cio.websocket.readText
import io.ktor.routing.Route
import io.ktor.websocket.WebSocketServerSession
import io.ktor.websocket.webSocket
import kif.common.model.Message
import kif.common.model.MessageType
import kotlinx.coroutines.channels.ClosedReceiveChannelException
import java.lang.Exception
object PushService {
var clients: List<WebSocketServerSession> = emptyList()
suspend fun notify(messageType: MessageType) {
try {
val data = Message(messageType).stringify()
for (client in clients) {
client.outgoing.send(Frame.Text(data))
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
fun Route.pushService() {
webSocket {
PushService.clients += this
try {
while (true) {
val text = (incoming.receive() as Frame.Text).readText()
println("onMessage($text)")
outgoing.send(Frame.Text(text))
}
} catch (_: ClosedReceiveChannelException) {
PushService.clients -= this
} catch (e: Throwable) {
println("onError ${closeReason.await()}")
e.printStackTrace()
PushService.clients -= this
}
}
}