Skip to content

Commit

Permalink
Merge pull request #49 from kuzzleio/48-fix-connect-not-throwing
Browse files Browse the repository at this point in the history
Fix connect method not throwing on failure
  • Loading branch information
Shiranuit authored Apr 7, 2021
2 parents 27348a6 + d00b9d2 commit 6f4de8d
Showing 1 changed file with 30 additions and 11 deletions.
41 changes: 30 additions & 11 deletions src/main/kotlin/io/kuzzle/sdk/protocol/WebSocket.kt
Original file line number Diff line number Diff line change
Expand Up @@ -61,16 +61,24 @@ open class WebSocket : AbstractProtocol {
this.reconnectionRetries = reconnectionRetries
}

private fun tryToReconnect() {
if (retryCount < reconnectionRetries) {
private fun tryToReconnect(): Boolean {
if (!autoReconnect)
return false

state = ProtocolState.RECONNECTING
trigger("networkStateChange", state.toString())

while (retryCount < reconnectionRetries) {
retryCount++
state = ProtocolState.RECONNECTING
trigger("networkStateChange", state.toString())
Thread.sleep(reconnectionDelay)
thread(start = true) {
try {
connect()
return true
} catch (e: Exception) {
// Nothing to do, just retry
}
}
return false
}

@KtorExperimentalAPI
Expand All @@ -81,6 +89,7 @@ open class WebSocket : AbstractProtocol {
// @TODO Create enums for events
state = ProtocolState.OPEN
trigger("networkStateChange", ProtocolState.OPEN.toString())
retryCount = 0
thread(start = true) {
while (ws != null) {
val payload = queue.poll()
Expand All @@ -92,6 +101,7 @@ open class WebSocket : AbstractProtocol {
}
}
wait.complete(null)
var reconnected = false
try {
for (frame in incoming) {
when (frame) {
Expand All @@ -102,11 +112,13 @@ open class WebSocket : AbstractProtocol {
}
}
} catch (e: Exception) {
tryToReconnect()
reconnected = tryToReconnect()
}
if (!reconnected) {
state = ProtocolState.CLOSE
trigger("networkStateChange", ProtocolState.CLOSE.toString())
ws = null
}
state = ProtocolState.CLOSE
trigger("networkStateChange", ProtocolState.CLOSE.toString())
ws = null
}
GlobalScope.launch {
try {
Expand Down Expand Up @@ -135,8 +147,15 @@ open class WebSocket : AbstractProtocol {
is ConnectException,
is SocketException,
is IOException -> {
tryToReconnect()
wait.complete(null)
if (state != ProtocolState.RECONNECTING) {
if (!tryToReconnect()) {
wait.completeExceptionally(e)
} else {
wait.complete(null)
}
} else {
wait.completeExceptionally(e)
}
} else -> throw e
}
}
Expand Down

0 comments on commit 6f4de8d

Please sign in to comment.