title: Websocket server: Handle close event per session
body: <p>Is there a way to handle the server-side close event of a websocket per-session? This is how I currently implemented it:</p>
  
  <pre><code>@ServerEndpoint("/ws")
  public class WebsocketServerEndpoint {
      @OnOpen
      public void onOpen(Session session) {
          System.out.println("Websocket opened");
          CustomWebsocketHandler handler = new CustomWebsocketHandler(session); // see below
          // ...
      }
  
      @OnClose
      public void onClose(Session session, CloseReason reason) {
          System.out.println("Websocket closed. Reason: " + reason);
      }
  }
  </code></pre>
  
  <p>But I want to wrap new <code>Session</code> instances inside a custom object. For messages, I can add the handler directly to the specific session via <code>addMessageHandler</code>. But how can I add a handler for the <code>onClose</code> event on that specific session?:</p>
  
  <pre><code>class CustomWebsocketHandler {
      public CustomWebsocketHandler(Session session) {
          session.addMessageHandler((MessageHandler.Whole&lt;String&gt;) this::handleMessage);
          // How to hook up close event to handleClose()?
      }
  
      private void handleMessage(String message) { /* ... */ }
  
      private void handleClose() { /* ... */ }
  }
  </code></pre>
  
  <p>One idea I had was to track every session in the <code>WebsocketServerEndpoint</code> and their respective <code>CustomWebsocketHandler</code> instances, and go through them for every close-event, forwarding the event. However this is very cumbersome and feels error prone:</p>
  
  <pre><code>@ServerEndpoint("/ws")
  public class WebsocketServerEndpoint {
      private List&lt;Pair&lt;Session, CustomWebsocketHandler&gt;&gt; sessions = new ArrayList&lt;&gt;();
  
      @OnOpen
      public void onOpen(Session session) {
          // ...
          sessions.add(Pair.of(session, handler)); // not hashable I suppose
      }
  
      @OnClose
      public void onClose(Session session, CloseReason reason) {
          // ...
          for (Iterator&lt;Pair&lt;Session, CustomWebsocketHandler&gt;&gt; it = sessions.iterator(); it.hasNext(); ) {
              Pair&lt;Session, CustomWebsocketHandler&gt; pair = it.next();
              if (pair.getLeft() == session) {
                  pair.getRight().handleClose();
                  it.remove();
                  break;
              }
          }
      }
  }
  </code></pre>
  
  <p>On the client side of things this is easy, because each connection can use its own instance of a <code>ClientEndpoint</code>-annotated class:</p>
  
  <pre><code>webSocketContainer.connectToServer(endpointInstance, websocketURI);
  </code></pre>
  
  <p>Does something similar exist for the server side, or is it otherwise cleanly possible to handle the serverside <code>onClose</code> (and eventually also <code>onError</code>) event per session?</p>