Search code examples
arrayskotlinencodingvert.xevent-bus

Vertx event bus and encoding issues when encoding/decoding string to Kotlin ByteArray


I'm using Kotlin and vertx. In my vertx app, I'm trying to send a ByteArray to another event consumer.

To do this i'm converting it to a string, and then once its received in the 2nd handler I'm converting it back to a ByteArray but the objects aren't equal. They are very different and I have no idea why.

My 2 event handlers are:

        eb.consumer<JsonObject>("epos.print.print-image-from-path") { message ->
        GlobalScope.launch(vertx.dispatcher()) {
            var imagePath = message.body().get<String>("imagePath")

            var convertor = image2escpos.Image2ESCPOS()
            var bytes = convertor.printImage(imagePath)

            println( bytes.joinToString("") { String.format("%02X", (it.toInt() and 0xFF)) })

            queueJob(bytes.toTypedArray())

            temp1 = bytes

            eb.publish("epos.print.print-image-from-bitmap", json { obj("bytes" to String(bytes)) })
        }
    }

    eb.consumer<JsonObject>("epos.print.print-image-from-bitmap") { message ->
        GlobalScope.launch(vertx.dispatcher()) {
            var bytes = message.body().get<String>("bytes")
            var byteArray = bytes.toByteArray(StandardCharsets.UTF_8)

            println( byteArray.joinToString("") { String.format("%02X", (it.toInt() and 0xFF)) })

            println("OUTPUT")
            println(temp1)
            println(byteArray)
            println(temp1==byteArray)
        }
    }

and I have the private variable: private lateinit var temp1:ByteArray so that I can compare the 2 variables.

I'm invoking the "epos.print.print-image-from-path" method by sending an event with a json body such as: { "imagePath" : "/Users/XXXXXXX/Downloads/QR-Zed80.BMP" }

What am i missing when encoding/decoding objects. I'm not entirely sure how a string relates to a ByteArray but I need to pass a ByteArray between 2 handlers and String seem to be the only way on the event bus.

Thanks for your help in advance!

Rob


Solution

  • If you aren't using clustered Vert.x, you can just send and receive ByteArray.

    You may need to implement a no-op codec, though: https://alexey-soshin.medium.com/understanding-vert-x-event-bus-c31759757ce8