Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 14 additions & 7 deletions src/main/kotlin/org/phoenixframework/PhxSocket.kt
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@ const val DEFAULT_TIMEOUT: Long = 10000
/** Default heartbeat interval set to 30s */
const val DEFAULT_HEARTBEAT: Long = 30000

/** The code used when the socket was closed without error */
const val WS_CLOSE_NORMAL = 1000

/** The code used when the socket was closed after the heartbeat timer timed out */
const val WS_CLOSE_HEARTBEAT_ERROR = 5000

open class PhxSocket(
url: String,
params: Payload? = null,
Expand Down Expand Up @@ -154,8 +160,8 @@ open class PhxSocket(
/**
* Disconnects the Socket
*/
fun disconnect() {
connection?.close(1000, null)
fun disconnect(code: Int = WS_CLOSE_NORMAL) {
connection?.close(WS_CLOSE_NORMAL, null)
connection = null

}
Expand Down Expand Up @@ -337,15 +343,16 @@ open class PhxSocket(
}

/** Triggers a message when the socket is closed */
private fun onConnectionClosed() {
private fun onConnectionClosed(code: Int) {
this.logItems("Transport: close")
this.triggerChannelError()

// Terminate any ongoing heartbeats
this.heartbeatTimer?.cancel()

// Attempt to reconnect the socket
if (autoReconnect) reconnectTimer?.scheduleTimeout()
// Attempt to reconnect the socket. If the socket was closed normally,
// then do not attempt to reconnect
if (autoReconnect && code != WS_CLOSE_NORMAL) reconnectTimer?.scheduleTimeout()

// Inform all onClose callbacks that the Socket closed
this.onCloseCallbacks.forEach { it() }
Expand Down Expand Up @@ -419,7 +426,7 @@ open class PhxSocket(
pendingHeartbeatRef?.let {
pendingHeartbeatRef = null
logItems("Transport: Heartbeat timeout. Attempt to re-establish connection")
disconnect()
disconnect(WS_CLOSE_HEARTBEAT_ERROR)
return@schedule
}

Expand All @@ -444,7 +451,7 @@ open class PhxSocket(
}

override fun onClosed(webSocket: WebSocket?, code: Int, reason: String?) {
this.onConnectionClosed()
this.onConnectionClosed(code)
}

override fun onFailure(webSocket: WebSocket?, t: Throwable, response: Response?) {
Expand Down