Skip to content

Commit

Permalink
Merge pull request #11 from maca88/improvements/crash-fix
Browse files Browse the repository at this point in the history
Fix crash when sending a hub message after connection closure
  • Loading branch information
lepicekmichal authored Dec 3, 2024
2 parents 3fc4665 + c5919a2 commit 66ddf44
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -363,15 +363,19 @@ class HubConnection private constructor(

override fun sendHubMessage(message: HubMessage) {
if (connectionState.value != HubConnectionState.CONNECTED) {
logger.log(Logger.Severity.ERROR, "Trying to send and message while the connection is not active. ($message)", null)
logger.log(Logger.Severity.ERROR, "Trying to send a message while the connection is not active. ($message)", null)
return
}

val serializedMessage: ByteArray = protocol.writeMessage(message)
scope.launch {
if (::transport.isInitialized) transport.send(serializedMessage)
logger.log(Logger.Severity.INFO, "Sent hub data: $message", null)
resetKeepAlive()
try {
if (::transport.isInitialized) transport.send(serializedMessage)
logger.log(Logger.Severity.INFO, "Sent hub data: $message", null)
resetKeepAlive()
} catch (e: Exception) {
logger.log(Logger.Severity.ERROR, "Failed to send hub data: $message", e)
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,11 @@ internal class WebSocketTransport(
}

override suspend fun send(message: ByteArray) {
session?.send(message) ?: throw IllegalStateException("WebSocket connection has not been started")
try {
session?.send(message) ?: throw IllegalStateException("WebSocket connection has not been started")
} catch (e: EOFException) {
throw IllegalStateException("WebSocket connection has been closed", e)
}
}

override fun receive(): Flow<ByteArray> = session?.incoming
Expand Down

0 comments on commit 66ddf44

Please sign in to comment.