如何使用play framework websocket创建新的聊天室?

时间:2019-06-02 18:12:16

标签: websocket playframework akka

我在play框架2.6.x中使用websocket尝试了聊天示例。工作正常。现在,对于实际应用程序,我需要根据用户请求创建多个聊天室。用户将可以使用ID或其他内容访问不同的聊天室。我认为这可能与为每个房间创建新流程有关。相关代码在这里:

   private val (chatSink, chatSource) = {
    val source = MergeHub.source[WSMessage]
      .log("source")
      .map { msg =>
      try {
        val json = Json.parse(msg)
        inputSanitizer.sanText((json \ "msg").as[String])
      } catch {
        case e: Exception => println(">>" + msg)
          "Malfunction client"
      }
    }
     .recoverWithRetries(-1, { case _: Exception ⇒ Source.empty })

    val sink = BroadcastHub.sink[WSMessage]
    source.toMat(sink)(Keep.both).run()
  }

  private val userFlow: Flow[WSMessage, WSMessage, _] = {
    Flow.fromSinkAndSource(chatSink, chatSource)
  }

但是我真的不知道如何创建带有ID的新流程并在以后访问它。有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

我终于明白了。如果有人遇到类似问题,请在此处发布解决方案。 我的解决方案是使用AsyncCacheApi通过密钥将Flow存储在缓存中。必要时生成一个新的Flow而不是仅创建一个接收器和源:

val chatRoom = cache.get[Flow[WSMessage, WSMessage, _]](s"id=$id")
chatRoom.map{room=>
    val flow = if(room.nonEmpty) room.get else createNewFlow
    cache.set(s"id=$id", flow)
    Right(flow)
}
def createNewFlow: Flow[WSMessage, WSMessage, _] = {
    val (chatSink, chatSource) = {
      val source = MergeHub.source[WSMessage]
        .map { msg =>
         try {
           inputSanitizer.sanitize(msg)
         } catch {
           case e: Exception => println(">>" + msg)
             "Malfunction client"
         }
       }
       .recoverWithRetries(-1, { case _: Exception ⇒ Source.empty })

     val sink = BroadcastHub.sink[WSMessage]
     source.toMat(sink)(Keep.both).run()
   }
   Flow.fromSinkAndSource(chatSink, chatSource)
 }