简体   繁体   中英

(Scala) Recognize the type a serialized object by Kryo which is sent through network using UDP

Currently I am having a problem of recognizing a receiving serialized object which is sent through network using UDP.

I have an abstract class called MsgType:

sealed abstract class MsgType
case class Msg(message : String) extends MsgType
case class End() extends MsgType

in that, Msg means a normal message whilst End means a termination request at client side.

===========================================================================

At server side, I have a function call isMessage to detect whether it's a normal message or the termination request:

def isMessage(message: AnyRef): Boolean = {
    message match{
      case End => false
      case Msg(message) => true
    }
}

=========================================================================== Here is the code using Kryo for receiving the message sent from client:

val inputString = kyro.readObject(input, classOf[MsgType]) println("incoming Message: " + isMessage(inputString))

However, when I run the code, there is an exception named:

Exception in thread "main" com.esotericsoftware.kryo.KryoException: Error 
constructing instance of class: MsgType

I know it's because MsgType is an abstract class....

Could anyone suggest me a better solution to deal with this problem of recognizing the type of received serialized object?

Thanks and Best Regards, Long.

Unfortunately Kryo doesn't work this way. It should know the type of object being deserialized before deserialization is started. It means you need to save this information in your serialized data as well. Conviently Kryo provides writeClassAndObject and readClassAndObject that do exactly that.

Also I expect that you'll have another issue related to the usage of the case classes. Unless you provided custom deserializators, Kryo will fail because your Msg case class doesn't have a default constructor (ie one with no parameters). You may consider using twitter chill - a Scala wrapper for Kryo. See alao Handling case classes in twitter chill (Scala interface to Kryo)?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM