Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix connect method not throwing on failure #49

Merged
merged 11 commits into from
Apr 7, 2021
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