Last active
November 22, 2021 07:47
-
-
Save vaibhavgoyal09/063f5a3a2be4c1306899fdbf3b5c9252 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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