Akka Streams和Scala Play服务器

时间:2018-05-15 00:18:15

标签: scala playframework akka akka-stream

我有一个用scala play 2.6编写的服务器

我正在尝试使用websocket

  1. 接收客户的请求
  2. 处理该请求
  3. 如果仅将错误广播到,则将结果广播到所有客户端 发送请求的客户端如果离开
  4. 我现在有消息向所有客户广播,有人知道如何只在错误情况下回复发件人吗?

      val processFlow = Flow[String].map(process).map(_.toString)
    
      val (sink, source) = { 
        MergeHub.source[String]
          .via(processFlow)
          .toMat(BroadcastHub.sink[String])(Keep.both)
          .run()
      }
    
      val websocketFlow = Flow.fromSinkAndSource(sink, source)
    
      def ws = WebSocket.accept[String, String] { request =>  
        websocketFlow
      }
    
      def process(message: String): Either[String, String] = { 
        if (message == "error") { // replace with any error condition
          Left ("ERROR " ++ message)
        } else {
          Right (message ++ " processed")
        }   
      }
    

1 个答案:

答案 0 :(得分:1)

如果您在流程中跟踪发件人,则可以先将收到的邮件过滤,然后再将其发送到websocket:

case class ProcessResult(senderId: String, result: Either[String, String])

val (sink, source) = { 
  MergeHub.source[ProcessResult]
    .toMat(BroadcastHub.sink[ProcessResult])(Keep.both)
    .run()
}
val websocketFlow = Flow.fromSinkAndSource(sink, source)

def ws = WebSocket.accept[String, String] { request =>
  // create a random id to identify the sender
  val senderId = UUID.randomUUID().toString
  Flow[String]
    .map(process)
    .map(result => ProcessResult(senderId, result))
    // broadcast the result to the other websockets
    .via(websocketFlow)
    // filter the results to only keep the errors for the sender
    .collect {
      case ProcessResult(sender, Left(error)) if sender == senderId => List(error)
      case ProcessResult(_, Left(error)) => List.empty
      case ProcessResult(_, Right(result)) => List(result)
    }.mapConcat(identity)
}

def process(message: String): Either[String, String] = { 
  if (message == "error") { // replace with any error condition
    Left ("ERROR " ++ message)
  } else {
    Right (message ++ " processed")
  }   
}