簡體   English   中英

在Play 2.4中無法從WebSocket返回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]變量中獲取並返回json值。 但是,我無法從Future[JsValue]變量返回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)
}

futureJsonVariableFuture[JsValue]類型的變量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. 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. 如何在Scala中使用WebSocket方法返回json? 如何使用Actor類實例來實現? 如果有人知道Play框架中WebSocket的最佳可用在線教程。 任何幫助表示贊賞。

使用tryAccept回到未來的任何結果當它被贖回,或錯誤:

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但是返回Future[Either[Result, (Iteratee[A, _], Enumerator[A])]] Either[Result, ...]允許您通過在Left分支中提供play.api.mvc.Result來處理發生意外情況而計算將來值A的情況。 必然的結果是,您還需要在Right包裝“快樂之路”(沒有出錯的地方),在這種情況下,您通常會從using返回的iteratee /枚舉器元組。

您可以使用tryAcceptWithActor函數執行類似的tryAcceptWithActor

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM