title: Play websockets: send to one client or many
body: <p>I'm trying to lean the Play Framework, using Scala.</p>
  
  <p>For small projects, my go-to framework is currently Tornado. I use it because of how easy it makes it to use websockets. Here's how I'd use a websocket handler in Tornado:</p>
  
  <pre><code>class SocketHandler(tornado.websocket.WebSocketHandler):
    """
    Handles websocket connections.
    """
    CLIENTS = set()
  
    def open(self, *args, **kwargs):
      self.CLIENTS.add(self)
      self.send_data() // Perform special "on open" action.
  </code></pre>
  
  <p>Then, for each received messages, I'd do this from the websocket class:</p>
  
  <pre><code>def some_action(self, message):
    do_things()
    self.write_message(response_data) # If needed.
  </code></pre>
  
  <p>If an even occurs for which I need to update all clients, I'd do this:</p>
  
  <pre><code>new_data = database_callback_that_affects_all_clients()
  for client in SocketHandler.CLIENTS:
    try:
      client.write_message(new_data)
    except WebSocketClosedError: pass # You can't always be sure which ones are closed.
  </code></pre>
  
  <p>One case sends the data back to the socket that made the request, one case sends the data to all websockets. But I use the same socket for both cases.</p>
  
  <p>With Play, how should I handle that distinction?</p>
  
  <p>The examples from the Websocket documentation webpage show how to send a message back to the sender and the chat sample application shows how to use the <code>BroadcastHub.sink</code> object to send a message to everything. But what if you need to do both, depending on the case?</p>
  
  <ul>
  <li>Should you keep a <code>Set</code> of <code>ActorRef</code> objects, like in Tornado? That seems the least Play-way of doing things.</li>
  <li>Or should you use two websockets, one for for responding to messages individually and one to broadcast messages to all clients in one action?</li>
  </ul>
  
  <p>If the proper solution is the second one, I'm guessing that play requires opening two websockets for that.</p>