New file |
| | |
| | | package com.zy.asrs.wcs.core.map.websocket; |
| | | |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import org.springframework.stereotype.Component; |
| | | |
| | | import javax.websocket.*; |
| | | import javax.websocket.server.ServerEndpoint; |
| | | import java.util.concurrent.ConcurrentHashMap; |
| | | |
| | | @Slf4j |
| | | @Component |
| | | @ServerEndpoint(value = "/ws/map/websocket") |
| | | public class MapWebSocket { |
| | | |
| | | private static final long MAX_IDLE_TIMEOUT = 120 * 1000; |
| | | |
| | | private static final ConcurrentHashMap<String, Session> sessions = new ConcurrentHashMap<>(); |
| | | |
| | | @OnOpen |
| | | public void onOpen(Session session) { |
| | | session.setMaxIdleTimeout(MAX_IDLE_TIMEOUT); |
| | | sessions.put(session.getId(), session); |
| | | log.info("Opened new session in instance " + session.getId()); |
| | | } |
| | | |
| | | @OnMessage |
| | | public void onMessage(String message, Session session) { |
| | | if (!message.equals("1")) { |
| | | log.info("Received WebSocket message: {}", message); |
| | | } |
| | | } |
| | | |
| | | @OnClose |
| | | public void onClose(Session session) { |
| | | sessions.remove(session.getId()); |
| | | log.info("Closed WebSocket session: {}", session.getId()); |
| | | } |
| | | |
| | | @OnError |
| | | public void onError(Session session, Throwable error) { |
| | | error.printStackTrace(); |
| | | log.error("Error in WebSocket session: {}", session.getId(), error); |
| | | try { |
| | | session.close(); |
| | | } catch (Exception e) { |
| | | log.error("Error closing session: {}", session.getId(), e); |
| | | } finally { |
| | | sessions.remove(session.getId()); |
| | | } |
| | | } |
| | | |
| | | public static void sendMessage(Session session, String message) { |
| | | if(session.isOpen()){ |
| | | try { |
| | | session.getBasicRemote().sendText(message); |
| | | } catch (Exception e) { |
| | | log.error("Failed to send message to session: {}", session.getId(), e); |
| | | } |
| | | } |
| | | } |
| | | |
| | | public static void broadcast(String message) { |
| | | sessions.forEach((id, session) -> { |
| | | try { |
| | | session.getBasicRemote().sendText(message); |
| | | } catch (Exception e) { |
| | | log.error("Failed to send message to session: {}", id, e); |
| | | } |
| | | }); |
| | | } |
| | | |
| | | } |