Update the server code to avoid disconnection from players.
This commit is contained in:
parent
2058a6a789
commit
ca8472e0d4
1 changed files with 8 additions and 12 deletions
|
|
@ -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<NettyApplicationEngine, NettyApplicationEngine
|
|||
|
||||
class LocalServer {
|
||||
private var server: Server? = null
|
||||
private val scope = CoroutineScope(Dispatchers.IO)
|
||||
private var networkJob: Job? = null
|
||||
private val outgoingMessageBuffer = MutableSharedFlow<Frame>()
|
||||
private val json = Json { explicitNulls = false }
|
||||
private val outgoingMessageBuffer = MutableSharedFlow<Message>()
|
||||
|
||||
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<NettyApplicationEngine, NettyApplicationEngine.Configuration> {
|
||||
return embeddedServer(
|
||||
factory = Netty,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue