001package var.web.ws.chat;
002
003import java.io.IOException;
004import java.util.ArrayList;
005import java.util.List;
006
007import javax.websocket.OnClose;
008import javax.websocket.OnError;
009import javax.websocket.OnMessage;
010import javax.websocket.OnOpen;
011import javax.websocket.Session;
012import javax.websocket.server.ServerEndpoint;
013
014@ServerEndpoint("/chat")
015public class ChatServer {
016        private static List<Session> clients = new ArrayList<>();
017
018        @OnOpen
019        public void open(Session session) {
020                synchronized (clients) {
021                        clients.add(session);
022                }
023                try {
024                        session.getBasicRemote().sendText("Verbindung wurde hergestellt.");
025                } catch (IOException e) {
026                        e.printStackTrace(System.err);
027                }
028        }
029
030        @OnClose
031        public void close(Session session) {
032                synchronized (clients) {
033                        clients.remove(session);
034                }
035        }
036
037        @OnMessage
038        public void message(Session session, String message) throws IOException {
039                synchronized (clients) {
040                        for (Session client : clients) {
041                                if (client.isOpen() && !client.getId().equals(session.getId()))
042                                        client.getBasicRemote().sendText("client#" + session.getId() + ": " + message);
043                        }
044                }
045        }
046
047        @OnError
048        public synchronized void error(Session session, Throwable ex) throws IOException {
049                synchronized (clients) {
050                        for (Session client : clients) {
051                                if (client.isOpen())
052                                        client.getBasicRemote().sendText("client#" + session.getId() + ": " + ex.getMessage());
053                        }
054                }
055        }
056}