我有一个用scala play 2.6编写的服务器
我正在尝试使用websocket
我现在有消息向所有客户广播,有人知道如何只在错误情况下回复发件人吗?
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")
}
}
答案 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")
}
}