Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @ServerEndpoint("/websocket")
- public class WebSocketTest {
- private static Set<Session> clients = Collections.synchronizedSet(new HashSet<Session>());
- static{
- TimerTask timerTask = new MyTimerTask();
- //running timer task as daemon thread
- Timer timer = new Timer(true);
- timer.scheduleAtFixedRate(timerTask, 0, 5*1000);
- }
- @OnMessage
- public void onMessage(String message, Session session) throws IOException {
- synchronized(clients){
- // Iterate over the connected sessions and broadcast the received message
- if(!message.equals("pong")){
- for(Session client : clients){
- if (!client.equals(session)){
- client.getBasicRemote().sendText(message);
- }
- }
- }
- }
- }
- @OnOpen
- public void onOpen (Session session) {
- // Add session to the connected sessions set
- clients.add(session);
- }
- @OnClose
- public void onClose (Session session) {
- // Remove session from the connected sessions set
- clients.remove(session);
- }
- public static void notifyClients(String message) throws IOException {
- synchronized(clients){
- // Iterate over the connected sessions and broadcast the received message
- for(Session client : clients){
- client.getBasicRemote().sendText(message);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement