Nicolas
06/18/2025, 12:16 PMfun Application.configureWebSocket(){
install(WebSockets) {
pingPeriod = 15.seconds
timeout = 15.seconds
maxFrameSize = kotlin.Long.MAX_VALUE
masking = false
}
}
routing {
webSocket("ws") {
val token = call.request.queryParameters["token"]
if (token == null) {
close(CloseReason(CloseReason.Codes.VIOLATED_POLICY, "No Token"))
return@webSocket
}
val decodedJWT = try { JwtFactory.buildverifier().verify(token) }
catch (e: Exception) {
close(CloseReason(CloseReason.Codes.VIOLATED_POLICY, "Invalid Token: ${e.message}"))
return@webSocket
}
val userId: UUID = try { UUID.fromString(decodedJWT.getClaim(JwtClaimConstant.claimUserId).asString()) }
catch (e: Exception) {
close(CloseReason(CloseReason.Codes.VIOLATED_POLICY, "Invalid Token: ${e.message}"))
return@webSocket
}
val sessionId = decodedJWT.id?.let {
runCatching { UUID.fromString(it) }.getOrNull()
} ?: run {
close(CloseReason(CloseReason.Codes.VIOLATED_POLICY, "Invalid or missing sessionId (jti)"))
return@webSocket
}
<http://logger.info|logger.info>("$userId is connected")
try {
println("$userId start")
incoming.consumeEach {
when (it) {
is Frame.Text -> {
val text = it.readText()
println("tototot $userId Received: $text")
}
is Frame.Close -> {
println("tototot $userId WebSocket closed by server with reason: ${it.readReason()}")
}
is Frame.Ping -> {
println("tototot $userId ping: $it")
}
is Frame.Pong -> {
println("tototot $userId pong: $it")
} else -> {
println("tototot $userId else: $it")
}
}
}
} catch (e: Exception) {
println("$userId error $e")
} finally {
println("$userId finally remove")
}
println("$userId end")
}
}
and I found something weird If I open a websocket on my iOS phone, turnoff the internet (and close my phone) I keep logging this on KTOR:
io.ktor.websocket.WebSocket - WebSocket Pinger: received valid pong frame Frame PONG
For me if I close my phone the webscket should try a ping and should not receive a pong and close, For me the goal of ping pong is to avoid all this. I am not sure if I have doing everything good 🙂
I am hosting my server on Render
Thank you in advance for your time