diff --git a/server/src/main/kotlin/com/pixelized/server/lwa/server/Server.kt b/server/src/main/kotlin/com/pixelized/server/lwa/server/Server.kt index 16e39cf..5c3bd34 100644 --- a/server/src/main/kotlin/com/pixelized/server/lwa/server/Server.kt +++ b/server/src/main/kotlin/com/pixelized/server/lwa/server/Server.kt @@ -2,6 +2,8 @@ package com.pixelized.server.lwa.server import com.pixelized.server.lwa.SERVER_PORT import com.pixelized.server.lwa.extention.decodeFromFrame +import com.pixelized.server.lwa.extention.encodeToFrame +import com.pixelized.server.lwa.protocol.Message import io.ktor.server.application.install import io.ktor.server.engine.EmbeddedServer import io.ktor.server.engine.embeddedServer @@ -14,9 +16,6 @@ import io.ktor.server.websocket.pingPeriod import io.ktor.server.websocket.timeout import io.ktor.server.websocket.webSocket import io.ktor.websocket.Frame -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.Job import kotlinx.coroutines.channels.consumeEach import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.launch @@ -29,18 +28,15 @@ typealias Server = EmbeddedServer() + private val json = Json { explicitNulls = false } + private val outgoingMessageBuffer = MutableSharedFlow() fun create(): LocalServer { server = build { - println("Server launched") - val job = launch { // send local message to the clients - outgoingMessageBuffer.collect { frame -> - send(frame) + outgoingMessageBuffer.collect { message -> + send(json.encodeToFrame(message)) } } runCatching { @@ -50,7 +46,7 @@ class LocalServer { val message = Json.decodeFromFrame(frame = frame) println(message) // broadcast to clients the message - outgoingMessageBuffer.emit(frame) + outgoingMessageBuffer.emit(message) } } }.onFailure { exception -> @@ -77,7 +73,7 @@ class LocalServer { private fun build( port: Int = SERVER_PORT, - handler: suspend DefaultWebSocketServerSession.() -> Unit + handler: suspend DefaultWebSocketServerSession.() -> Unit, ): EmbeddedServer { return embeddedServer( factory = Netty,