From 28cd840d5d383968bf1a2269193b18fa8e530725 Mon Sep 17 00:00:00 2001
From: Junjie <xjj@123>
Date: 星期三, 03 四月 2024 14:25:43 +0800
Subject: [PATCH] Merge remote-tracking branch 'origin/Four-Way-Rack' into Four-Way-Rack

---
 zy-asrs-wcs/src/main/java/com/zy/asrs/wcs/core/map/websocket/MapWebSocket.java |   72 ++++++++++++++++++++++++++++++++++++
 1 files changed, 72 insertions(+), 0 deletions(-)

diff --git a/zy-asrs-wcs/src/main/java/com/zy/asrs/wcs/core/map/websocket/MapWebSocket.java b/zy-asrs-wcs/src/main/java/com/zy/asrs/wcs/core/map/websocket/MapWebSocket.java
new file mode 100644
index 0000000..193a1a4
--- /dev/null
+++ b/zy-asrs-wcs/src/main/java/com/zy/asrs/wcs/core/map/websocket/MapWebSocket.java
@@ -0,0 +1,72 @@
+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);
+            }
+        });
+    }
+
+}

--
Gitblit v1.9.1