【问题标题】:Play framework 2.2 single websocket messages dispatchingPlay framework 2.2 单websocket消息调度
【发布时间】:2013-10-23 08:38:10
【问题描述】:

在 play 框架中,我们可以看到 websocket-chat 应用程序,它向我们展示了 Concurrent.broadcast 用于处理 websocket 消息的用法。

但我想使用 websockets 将消息独立地发送到每个连接的 websocket。最简单的例子是私人消息,当用户发送如下消息时:{user: "First", to: "Second", message: "Hi"}。

我查看了对象 play.api.libs.iteratee.Concurrent,看起来最适合有 Concurrent.unicast 来执行此操作。但是当我们有 Concurrent.broadcast - 我们有可以推送消息的频道。在 Concurrent.unicast 的情况下 - 我们只有 Enumerator。

那么,如何在 Scala 中使用 Play Framework 2.2 在 websocket 之间发送私人消息?

【问题讨论】:

    标签: scala concurrency websocket playframework-2.0


    【解决方案1】:

    我从播放框架示例的源代码中找到了另一种方法来归档私人消息传递问题。通过为每个用户使用过滤的枚举器:

    val filteredEnumerator = enumerator &> Enumeratee.filter[JsValue]( e =>  {
        if ( (e \ "kind").as[String] == "talk") {
          val isToAll = (e \ "recipient").as[String] == "all"
          val isToRecipient = (e \ "recipient").as[String] == username
          val isFromRecipient = (e \ "user").as[String] == username
          isToAll || isToRecipient || isFromRecipient
        } else {
          true
        }
      })
      sender ! Connected(filteredEnumerator)
    

    因此,如果类型是“谈话”(我们只想过滤消息),接收者是“全部”,接收者是用户名本身,或者如果用户是用户名本身,则消息将被传递给枚举器,因此发送消息的人也会看到该消息。

    【讨论】:

      【解决方案2】:

      聊天室应用程序中的回复通过以下方式发送给聊天室中的所有用户:

      // 向所有成员发送 Json 事件 public void notifyAll(String kind, String user, String text) {

      因此,如果您想实现私人消息,则必须实现“通知”方法,该方法将只向特定用户发送消息。像这样说:

      // Send a Json event to all members
      public void notify(String kind, String user, String userTo, String text) {
          for(WebSocket.Out<JsonNode> channel: members.values()) {
      
              ObjectNode event = Json.newObject();
              event.put("kind", kind);
              event.put("user", user);
              event.put("message", text);
      
              ArrayNode m = event.putArray("members");
              m.add(userTo);
      
              channel.write(event);
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-07-31
        • 2014-08-25
        • 1970-01-01
        • 1970-01-01
        • 2013-10-24
        • 2013-11-06
        • 1970-01-01
        相关资源
        最近更新 更多