Advertisement
Falseclock

WebSocket

Sep 2nd, 2022
1,180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.25 KB | None | 0 0
  1. @ServerEndpoint("/websocket")
  2. public class WebSocketTest {
  3.  
  4.     private static Set<Session> clients = Collections.synchronizedSet(new HashSet<Session>());
  5.  
  6.     static{
  7.         TimerTask timerTask = new MyTimerTask();
  8.         //running timer task as daemon thread
  9.         Timer timer = new Timer(true);
  10.         timer.scheduleAtFixedRate(timerTask, 0, 5*1000);
  11.     }
  12.  
  13.     @OnMessage
  14.     public void onMessage(String message, Session session) throws IOException {
  15.  
  16.         synchronized(clients){
  17.             // Iterate over the connected sessions and broadcast the received message
  18.             if(!message.equals("pong")){
  19.                 for(Session client : clients){
  20.                     if (!client.equals(session)){
  21.                         client.getBasicRemote().sendText(message);
  22.                     }
  23.                 }
  24.             }
  25.         }
  26.     }
  27.  
  28.     @OnOpen
  29.     public void onOpen (Session session) {
  30.         // Add session to the connected sessions set
  31.         clients.add(session);
  32.     }
  33.  
  34.     @OnClose
  35.     public void onClose (Session session) {
  36.         // Remove session from the connected sessions set
  37.         clients.remove(session);
  38.     }
  39.  
  40.  
  41.     public static void notifyClients(String message) throws IOException {
  42.  
  43.         synchronized(clients){
  44.             // Iterate over the connected sessions and broadcast the received message
  45.             for(Session client : clients){
  46.                 client.getBasicRemote().sendText(message);
  47.             }
  48.         }
  49.     }
  50. }
  51.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement