129 lines
3.4 KiB
Kotlin
129 lines
3.4 KiB
Kotlin
package de.pheerai.buzzer.plugins
|
|
|
|
import de.pheerai.buzzer.data.GameMasterSocket
|
|
import de.pheerai.buzzer.data.PlayerSocket
|
|
import io.ktor.application.*
|
|
import io.ktor.html.*
|
|
import io.ktor.http.cio.websocket.*
|
|
import io.ktor.http.content.*
|
|
import io.ktor.routing.*
|
|
import io.ktor.websocket.*
|
|
import kotlinx.coroutines.isActive
|
|
import kotlinx.html.*
|
|
import java.time.Duration
|
|
import java.util.*
|
|
|
|
fun Application.configureSockets() {
|
|
install(WebSockets) {
|
|
pingPeriod = Duration.ofSeconds(15)
|
|
timeout = Duration.ofSeconds(15)
|
|
maxFrameSize = Long.MAX_VALUE
|
|
masking = false
|
|
}
|
|
|
|
routing {
|
|
val playerSessions = Collections.synchronizedCollection(LinkedList<PlayerSocket>())
|
|
val gameMasterSessions = Collections.synchronizedCollection(LinkedList<GameMasterSocket>())
|
|
|
|
static("/assets") {
|
|
resources("css")
|
|
resources("js")
|
|
}
|
|
|
|
get("/") {
|
|
call.respondHtml {
|
|
createPlayerDocument()
|
|
}
|
|
}
|
|
|
|
get("/client/player") {
|
|
call.respondHtml {
|
|
createPlayerDocument()
|
|
}
|
|
}
|
|
|
|
get("/client/master") {
|
|
call.respondHtml {
|
|
createAdminDocument()
|
|
}
|
|
}
|
|
|
|
webSocket("/socket/player") {
|
|
playerSessions.add(PlayerSocket(this))
|
|
for (frame in incoming) {
|
|
when (frame) {
|
|
is Frame.Text -> {
|
|
val text = frame.readText()
|
|
log.info("Username: $text")
|
|
gameMasterSessions.filter { it.session.isActive }
|
|
.forEach { it.session.send(text) }
|
|
}
|
|
else -> {}
|
|
}
|
|
}
|
|
}
|
|
|
|
webSocket("/socket/master") {
|
|
gameMasterSessions.add(GameMasterSocket(this))
|
|
for (frame in incoming) {
|
|
when (frame) {
|
|
is Frame.Text -> {
|
|
val text = frame.readText()
|
|
playerSessions.filter { it.session.isActive }
|
|
.forEach { it.session.send(text) }
|
|
}
|
|
else -> {}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
fun HTML.createPlayerDocument() {
|
|
head {
|
|
meta { charset = "UTF-8" }
|
|
title { +"JS Client" }
|
|
link(
|
|
href = "/assets/player.css",
|
|
rel = "stylesheet",
|
|
type = "text/css"
|
|
)
|
|
script { src = "https://code.jquery.com/jquery-3.6.0.min.js" }
|
|
script { src = "/assets/playerClient.js" }
|
|
}
|
|
body {
|
|
div(classes = "parent") {
|
|
div(classes = "input") {
|
|
label { +"Player" }
|
|
div(classes = "bumper") {}
|
|
input {
|
|
id = "username"
|
|
placeholder = "<name>"
|
|
}
|
|
}
|
|
button(classes = "submit") {
|
|
onClick = "sendUsername()"
|
|
+"I know that!"
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
fun HTML.createAdminDocument() {
|
|
head {
|
|
meta { charset = "UTF-8" }
|
|
title { +"JS Client" }
|
|
script { src = "https://code.jquery.com/jquery-3.6.0.min.js" }
|
|
script { src = "/assets/adminClient.js" }
|
|
}
|
|
body {
|
|
ol {
|
|
id = "usernames"
|
|
}
|
|
button {
|
|
onClick = "resetReceived()"
|
|
+"Reset"
|
|
}
|
|
}
|
|
}
|