View Javadoc

1   //
2   //  ========================================================================
3   //  Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
4   //  ------------------------------------------------------------------------
5   //  All rights reserved. This program and the accompanying materials
6   //  are made available under the terms of the Eclipse Public License v1.0
7   //  and Apache License v2.0 which accompanies this distribution.
8   //
9   //      The Eclipse Public License is available at
10  //      http://www.eclipse.org/legal/epl-v10.html
11  //
12  //      The Apache License v2.0 is available at
13  //      http://www.opensource.org/licenses/apache2.0.php
14  //
15  //  You may elect to redistribute this code under either of these licenses.
16  //  ========================================================================
17  //
18  
19  package com.acme;
20  
21  import java.io.IOException;
22  import java.util.List;
23  import java.util.ListIterator;
24  import java.util.concurrent.CopyOnWriteArrayList;
25  
26  import javax.websocket.CloseReason;
27  import javax.websocket.OnClose;
28  import javax.websocket.OnMessage;
29  import javax.websocket.OnOpen;
30  import javax.websocket.RemoteEndpoint;
31  import javax.websocket.Session;
32  import javax.websocket.server.ServerEndpoint;
33  
34  @ServerEndpoint(value="/javax.websocket/", subprotocols={"chat"})
35  public class JavaxWebSocketChat
36  {
37      private static final List<JavaxWebSocketChat> members = new CopyOnWriteArrayList<>();
38      
39      volatile Session session;
40      volatile RemoteEndpoint.Async remote;
41      
42      @OnOpen
43      public void onOpen(Session sess)
44      {
45          this.session = sess;
46          this.remote = this.session.getAsyncRemote();
47          members.add(this);
48      }
49      
50      @OnMessage
51      public void onMessage(String data)
52      {
53          if(data.contains("disconnect"))
54          {
55              try
56              {
57                  session.close();
58              }
59              catch (IOException ignore)
60              {
61                  /* ignore */
62              }
63              return;
64          }
65          
66          ListIterator<JavaxWebSocketChat> iter = members.listIterator();
67          while(iter.hasNext())
68          {
69              JavaxWebSocketChat member = iter.next();
70              
71              // Test if member is now disconnected
72              if(!member.session.isOpen())
73              {
74                  iter.remove();
75                  continue;
76              }
77              
78              // Async write the message back
79              member.remote.sendText(data);
80          }
81      }
82      
83      @OnClose
84      public void onClose(CloseReason reason)
85      {
86          members.remove(this);
87      }
88  }