NaikSoftware / StompProtocolAndroid

STOMP protocol via WebSocket for Android
MIT License
597 stars 265 forks source link

The methods that support reconnection #213

Closed panyy closed 1 year ago

panyy commented 1 year ago
class SocketHelper(private val context: Context) {
    private var stompClient: StompClient? = null
    private var topicSchool: Disposable? = null
    private val reconnectDelay: Long = 30 * 1000
    private val reconnectExecutor = Executors.newSingleThreadScheduledExecutor()

    fun start() {
        val url = "ws://xxx.xxx.xxx/xxx/xxx"
        stompClient = Stomp.over(Stomp.ConnectionProvider.OKHTTP, url)
        stompClient?.lifecycle()?.subscribe { event ->
            if (event.type == LifecycleEvent.Type.OPENED) {
                if (topicSchool != null) {
                    topicSchool?.dispose()
                    topicSchool = null
                }
                topicSchool = stompClient?.topic("/topic/school/schoolid")
                    ?.subscribe({
                    }) {
                        Log.e("stomp", "STOMP topic school error", it)
                    }
            }
        }
        stompClient?.withClientHeartbeat(10000)?.withServerHeartbeat(10000)?.connect()
        reconnectExecutor.scheduleAtFixedRate(
            reconnectRunnable, reconnectDelay, reconnectDelay, TimeUnit.MILLISECONDS
        )
    }

    private var reconnectRunnable = Runnable {
        //reconnect
        if (stompClient?.isConnected == false) {
            stompClient?.connect()
        }
    }

    fun stop() {
        reconnectExecutor.shutdownNow()
        stompClient?.disconnect()
        topicSchool?.dispose()
    }
}