Skip to content

Instantly share code, notes, and snippets.

@vaibhavgoyal09
Last active November 22, 2021 07:47
Show Gist options
  • Save vaibhavgoyal09/063f5a3a2be4c1306899fdbf3b5c9252 to your computer and use it in GitHub Desktop.
Save vaibhavgoyal09/063f5a3a2be4c1306899fdbf3b5c9252 to your computer and use it in GitHub Desktop.
fun Route.gameSocketRoute() {
route("/v1/game") {
standardWebSocket { socket, clientId, _, payload ->
when (payload) {
is GameMove -> {
// Do something here
}
is DisconnectRequest -> {
// Do something here
}
}
}
}
}
fun Route.standardWebSocket(
handleFrame: suspend (
socket: DefaultWebSocketServerSession,
clientId: String,
frameTextReceived: String,
payload: BaseModel
) -> Unit
) {
webSocket {
try {
incoming.consumeEach { frame ->
if (frame is Frame.Text) {
val frameTextReceived = frame.readText()
val jsonObject = JsonParser.parseString(frameTextReceived).asJsonObject
val type = when (jsonObject.get("type").asString) {
TYPE_GAME_MOVE -> GameMove::class.java
TYPE_DISCONNECT_REQUEST -> DisconnectRequest::class.java
else -> BaseModel::class.java
}
val payload = gson.fromJson(frameTextReceived, type)
handleFrame(this, clientId, frameTextReceived, payload)
}
}
} catch (e: Exception) {
e.printStackTrace()
} finally {
// Handle Socket Closed
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment