无法从 Play 2.4 中的 WebSocket return Future[JsValue] 中的 json

Unable to return a json inside Future[JsValue] from a WebSocket in Play 2.4

我已经实现了 Play 框架的 WebSocket 以便使用 WebSocket 而不是 Http 执行服务器通信。我创建了一个函数 WebSocket.using[JsValue]。我的 json 响应存储在 Future[JsValue] 变量中,我正在尝试从 Future[JsValue] 变量中获取并 return json 值。但是,我无法从 Future[JsValue] 变量中 return json 数据。当我尝试将 WebSocket 函数创建为 WebSocket.using[Future[JsValue]] 时,在这种情况下我无法为其创建 json FrameFormatter

def socketTest = WebSocket.using[JsValue] { request =>
val in = Iteratee.ignore[JsValue]
val out = Enumerator[JsValue](
      Json.toJson(futureJsonVariable)
    ).andThen(Enumerator.eof)
(in, out)
}

futureJsonVariable 是一个 Future[JsValue] 类型的变量 在上面的代码中,运行时的错误是 No Json serializer found for type scala.concurrent.Future[play.api.libs.json.JsValue]. Try to implement an implicit Writes or Format for this type. 我如何 return a json 在 Scala 中使用 WebSocket 方法? 如何使用 Actor class 实例来实现?如果有人知道 Play 框架中 WebSocket 的最佳可用在线教程。感谢任何帮助。

使用tryAccept到return要么未来赎回时的结果,要么报错:

def socketTest = WebSocket.tryAccept[JsValue] { request =>
  futureJsonVariable.map { json =>
    val in = Iteratee.ignore[JsValue]
    val out = Enumerator(json).andThen(Enumerator.eof)
    Right((in, out))
  } recover {
    case err => Left(InternalServerError(err.getMessage))
  }
}

这类似于 using,但 return 是 Future[Either[Result, (Iteratee[A, _], Enumerator[A])]]Left 分支中的 Either[Result, ...] allows you to handle the case where something unexpected occurs calculating the future value A by providing a play.api.mvc.Result。推论是你还需要在 Right 中包装 "happy path" (没有出错的地方),在这种情况下,你通常 return 来自 [=] 的 iteratee/enumerator 元组12=].

您可以使用 tryAcceptWithActor 函数执行类似的操作。