如何将数据推送到枚举器

How to push data to enumerator

下面的代码是一个简单的 actor 示例,它希望使用枚举器与远程服务器进行通信。应该可以将新数据推送到枚举器。但是,我不确定该怎么做。我在 this 问题中找到了解决方案,但是 Enumerator.imperative 已被弃用并且根据 Play!文档它似乎被 Concurrent.unicast 取代,它没有 push 方法。

// WorkerActor
val stdin = Concurrent.unicast[Array[Byte]](onStart = channel => {
  channel.push("uname -a\n".toCharArray.map(_.toByte)) // First message
}) >>> Enumerator.eof

attachStream(stdin)

def receive = LoggingReceive {
  case message: Array[Byte] =>
    // TODO: push the message to the stream
    // stdin push message ?
    ...
}

感谢您提供的任何帮助。

您需要捕获频道,例如,您可以在演员内部做类似的事情:

// WorkerActor
case class GotChannel(channel: Channel[Array[Byte]])
case object ChannelClosed
case class ChannelError(msg: String)
val stdin = Concurrent.unicast[Array[Byte]](
  // you cannot change actor state from in here, it is on another thread
  onStart = channel => self ! GotChannel(channel),
  onComplete = () => self ! ChannelClosed,
  onError = (msg, _) => self ! ChannelError(msg)
) >>> Enumerator.eof

attachStream(stdin)

def receive = {
  case GotChannel(channel) =>
    channel.push("uname -a\n".toCharArray.map(_.toByte))
    context.become(active(channel))
}

def active(channel: Channel[Array[Byte]]): Actor.Receive = LoggingReceive {
  case message: Array[Byte] =>
    // push the message to the stream
    channel.push(message)
    ...
  // handle ChannelClosed and ChannelError here
}