下面的代码是一个想要使用枚举器与远程服务器通信的actor的简单示例。应该可以将新数据推送到枚举器。但是,我不知道该怎么做。我在this问题中找到了一个解决方案,但Enumerator.imperative已被弃用并且根据Play! docs似乎被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 ?
...
}
感谢您提供任何帮助。
答案 0 :(得分:2)
您需要捕获频道,例如,您可以在演员内部执行此操作:
// 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
}