All Downloads are FREE. Search and download functionalities are using the official Maven repository.

jvmCommonMain.com.arkivanov.mvikotlin.timetravel.proto.internal.io.ReaderThread.kt Maven / Gradle / Ivy

There is a newer version: 4.2.0
Show newest version
package com.arkivanov.mvikotlin.timetravel.proto.internal.io

import com.arkivanov.mvikotlin.timetravel.proto.internal.data.ProtoObject
import java.io.IOException
import java.net.Socket

class ReaderThread(
    private val socket: Socket,
    private val onRead: (T) -> Unit,
    private val onDisconnected: () -> Unit = {},
    private val onError: (IOException) -> Unit = {}
) : Thread() {

    override fun run() {
        val protoDecoder = ProtoDecoder()

        val protoFrameDecoder =
            ProtoFrameDecoder { data ->
                val protoObject = protoDecoder.decode(data)
                @Suppress("UNCHECKED_CAST")
                onRead(protoObject as T)
            }

        try {
            val input = socket.getInputStream().buffered()
            val buffer = ByteArray(size = 32768)
            while (!isInterrupted) {
                val len = input.read(buffer)
                if (len < 0) {
                    break
                }

                protoFrameDecoder.accept(buffer, len)
            }
        } catch (e: IOException) {
            onError(e)
        } finally {
            socket.closeSafe()
            onDisconnected()
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy