Skip to content

Instantly share code, notes, and snippets.

@NikkyAI
Last active October 25, 2019 16:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NikkyAI/91cd375a24bab6301c14e281cf2d4b93 to your computer and use it in GitHub Desktop.
Save NikkyAI/91cd375a24bab6301c14e281cf2d4b93 to your computer and use it in GitHub Desktop.
GlobalScope.launch(Dispatchers.Default) {
connectToGame(state, game)
}
suspend fun connectToGame(state: MultiplayerState.Connected, game: GameSessionInfo) {
val wsUrl = URLBuilder(state.baseUrl)
.path("ws", "game", game.id)
.build()
client.webSocket(
host = wsUrl.host,
port = wsUrl.port, path = wsUrl.fullPath,
request = {
authenticateWith(state)
if(wsUrl.protocol == URLProtocol.HTTPS)
url.protocol = URLProtocol.WSS
}
) {
logger.info { "connection opened" }
// setup
// sending authentication
outgoing.send(Frame.Text(state.session))
try {
val notationListJson = (incoming.receive() as Frame.Text).readText()
// processing
while (true) {
val notationJson = (incoming.receive() as Frame.Text).readText()
// processing
}
} catch (e: ClosedReceiveChannelException) {
val reason = closeReason.await()
logger.debug(e) { "onClose $reason" }
// TODO transition to state `ConnectionLost`
} catch (e: Throwable) {
val reason = closeReason.await()
logger.error(e) { "onClose $reason" }
// TODO transition to state `ConnectionLost`
} finally {
// NOTE: kotlin-js never reaches here
logger.info { "connection closing" }
}
}
// NOTE: kotlin-js never reaches here
logger.info { "connection closed" }
PentaViz.gameStateProperty.value = ClientGameState(2)
PentaViz.updateBoard()
// connection closed "normally" ?
PentaViz.multiplayerState.value = MultiplayerState.Connected(
baseUrl = state.baseUrl,
userId = state.userId,
session = state.session
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment