@@ -23,6 +23,12 @@ const val DEFAULT_TIMEOUT: Long = 10000
2323/* * Default heartbeat interval set to 30s */
2424const val DEFAULT_HEARTBEAT : Long = 30000
2525
26+ /* * The code used when the socket was closed without error */
27+ const val WS_CLOSE_NORMAL = 1000
28+
29+ /* * The code used when the socket was closed after the heartbeat timer timed out */
30+ const val WS_CLOSE_HEARTBEAT_ERROR = 5000
31+
2632open class PhxSocket (
2733 url : String ,
2834 params : Payload ? = null ,
@@ -154,8 +160,8 @@ open class PhxSocket(
154160 /* *
155161 * Disconnects the Socket
156162 */
157- fun disconnect () {
158- connection?.close(1000 , null )
163+ fun disconnect (code : Int = WS_CLOSE_NORMAL ) {
164+ connection?.close(WS_CLOSE_NORMAL , null )
159165 connection = null
160166
161167 }
@@ -337,15 +343,16 @@ open class PhxSocket(
337343 }
338344
339345 /* * Triggers a message when the socket is closed */
340- private fun onConnectionClosed () {
346+ private fun onConnectionClosed (code : Int ) {
341347 this .logItems(" Transport: close" )
342348 this .triggerChannelError()
343349
344350 // Terminate any ongoing heartbeats
345351 this .heartbeatTimer?.cancel()
346352
347- // Attempt to reconnect the socket
348- if (autoReconnect) reconnectTimer?.scheduleTimeout()
353+ // Attempt to reconnect the socket. If the socket was closed normally,
354+ // then do not attempt to reconnect
355+ if (autoReconnect && code != WS_CLOSE_NORMAL ) reconnectTimer?.scheduleTimeout()
349356
350357 // Inform all onClose callbacks that the Socket closed
351358 this .onCloseCallbacks.forEach { it() }
@@ -419,7 +426,7 @@ open class PhxSocket(
419426 pendingHeartbeatRef?.let {
420427 pendingHeartbeatRef = null
421428 logItems(" Transport: Heartbeat timeout. Attempt to re-establish connection" )
422- disconnect()
429+ disconnect(WS_CLOSE_HEARTBEAT_ERROR )
423430 return @schedule
424431 }
425432
@@ -444,7 +451,7 @@ open class PhxSocket(
444451 }
445452
446453 override fun onClosed (webSocket : WebSocket ? , code : Int , reason : String? ) {
447- this .onConnectionClosed()
454+ this .onConnectionClosed(code )
448455 }
449456
450457 override fun onFailure (webSocket : WebSocket ? , t : Throwable , response : Response ? ) {
0 commit comments