Debian Codegraph @

jetty-ee10/jetty-ee10-demos/jetty-ee10-demo-jetty-webapp/src/main/java/org/example/JakartaWebSocketChat.java

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