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.handlers; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; /** * * @author u329022 */ public class EchoMessageHandler extends TextWebSocketHandler { private Map<String, WebSocketSession> sessions; public EchoMessageHandler() { sessions = new ConcurrentHashMap<String, WebSocketSession>(); } /** * Invoked after WebSocket negotiation has succeeded and the WebSocket * connection is opened and ready for use. * * @throws Exception this method can handle or propagate exceptions; see * class-level Javadoc for details. ` */ public void OnOpen(WebSocketSession wss) throws Exception { if (!sessions.containsKey(wss.getId())) { sessions.put(wss.getId(), wss); } } /** * Invoked after the WebSocket connection has been closed by either side, or * after a transport error has occurred. Although the session may * technically still be open, depending on the underlying implementation, * sending messages at this point is discouraged and most likely will not * succeed. * * @throws Exception this method can handle or propagate exceptions; see * class-level Javadoc for details. */ public void onClose(WebSocketSession wss, CloseStatus status) throws Exception { //sessions.remove(wss.getId()); for (Entry<String, WebSocketSession> entry : this.sessions.entrySet()) { sessions.remove(entry.getKey()); } } /** * Invoked when a new WebSocket message arrives. * * @throws Exception this method can handle or propagate exceptions; see * class-level Javadoc for details. */ public void onMessage(WebSocketSession wss, TextMessage message) throws Exception { //wss.sendMessage(message); for (Entry<String, WebSocketSession> entry : this.sessions.entrySet()) { entry.getValue().sendMessage(message); } } /** * Handle an error from the underlying WebSocket message transport. * * @throws Exception this method can handle or propagate exceptions; see * class-level Javadoc for details. */ public void onError(WebSocketSession session, Throwable exception) throws Exception { } }