Java tutorial
/* * Copyright (c) 2013 ITOCHU Techno-Solutions Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.co.ctc_g.rack.websocket.sharedmessage; import java.util.List; import jp.co.ctc_g.jfw.core.internal.InternalException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Component; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.adapter.TextWebSocketHandlerAdapter; /** * <p> * ????ID?????? * </p> * @author ITOCHU Techno-Solutions Corporation. */ @Component(value = "/sharedmessage") public class SharedMessageHandler extends TextWebSocketHandlerAdapter { private static final Logger L = LoggerFactory.getLogger(SharedMessageHandler.class); /** * {@inheritDoc} */ @Override public void afterConnectionEstablished(WebSocketSession session) { L.info("WebSocket connection is open"); Groups.addGroup(new Group(getGroupId(session), session)); } /** * {@inheritDoc} */ @Override public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { L.info("handle message" + message.getPayload()); Groups.broadcast(getGroupId(session), message.getPayload()); } /** * {@inheritDoc} */ @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { L.info("WebSocket connection is closed"); Groups.remove(session.getId()); super.afterConnectionClosed(session, status); }; /** * {@inheritDoc} */ @Override public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { L.debug(exception.getMessage()); } private String getGroupId(WebSocketSession session) { HttpHeaders headers = session.getHandshakeHeaders(); if (headers == null) { throw new InternalException(SharedMessageHandler.class, "E-SHARED#0001"); } List<String> groupIds = headers.get("x-GroupId"); if (groupIds == null || groupIds.size() != 1) { throw new InternalException(SharedMessageHandler.class, "E-SHARED#0001"); } return groupIds.get(0); } }