Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.emmanuel.spring.chat.services; import java.io.IOException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.springframework.stereotype.Service; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; /** * * @author u329022 */ @Service public class ChatRoomServices { private static final Map<String, WebSocketSession> userSessionConnections = new ConcurrentHashMap<>(); public void onOpenConnection(WebSocketSession wss, String nickName) { if (nickName == null || nickName.trim().equals("")) { nickName = wss.getId(); } // Every User is mapped to a session and added to this container userSessionConnections.put(nickName, wss); } public void onCloseConnection(WebSocketSession wss, String nickName) { if (userSessionConnections.containsKey(nickName)) { userSessionConnections.remove(nickName); } } public void onMessage(WebSocketSession wss, String message) throws IOException { for (Map.Entry<String, WebSocketSession> entry : userSessionConnections.entrySet()) { entry.getValue().sendMessage(new TextMessage(message)); } } public void onError(WebSocketSession sessionn) { } }