【问题标题】:(Scala) Recognize the type a serialized object by Kryo which is sent through network using UDP(Scala) 识别 Kryo 使用 UDP 通过网络发送的序列化对象的类型
【发布时间】:2017-05-07 16:11:09
【问题描述】:

目前,我在识别使用 UDP 通过网络发送的接收序列化对象时遇到问题。

我有一个名为 MsgType 的抽象类:

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

其中,Msg 表示正常消息,而 End 表示客户端的终止请求。

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

在服务器端,我有一个函数调用 isMessage 来检测是正常消息还是终止请求:

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

================================================ ============================== 下面是使用 Kryo 接收客户端发送的消息的代码:

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

但是,当我运行代码时,出现了一个异常,名为:

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

我知道这是因为 MsgType 是一个抽象类......

谁能建议我更好的解决方案来处理识别接收到的序列化对象类型的问题?

感谢和最好的问候, 长。

【问题讨论】:

    标签: scala serialization udp pattern-matching kryo


    【解决方案1】:

    不幸的是,Kryo 不是这样工作的。在反序列化开始之前,它应该知道被反序列化的对象的类型。这意味着您还需要将此信息保存在序列化数据中。 Conviently Kryo 提供了 writeClassAndObjectreadClassAndObject,它们正是这样做的。

    此外,我希望您还会遇到与案例类的使用相关的另一个问题。除非您提供自定义反序列化器,否则 Kryo 将失败,因为您的 Msg 案例类没有默认构造函数(即没有参数的构造函数)。您可以考虑使用twitter chill - Kryo 的 Scala 包装器。见阿劳Handling case classes in twitter chill (Scala interface to Kryo)?

    【讨论】:

      猜你喜欢
      • 2016-07-16
      • 1970-01-01
      • 2011-03-16
      • 2014-12-16
      • 1970-01-01
      • 2016-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多