1
zj
2024-07-12 c2cf572d823f5ab410fd82ae169f012caf3386c7
websocketSerivce/src/main/java/org/example/websocket/server/WsServer.java
@@ -16,9 +16,7 @@
import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
@@ -70,20 +68,21 @@
    }
    public void sendMessageToAll(String message) {
        Map<String, Object> map = jsonToMap(message);
        if (map.get("pid").equals("00000001")) {
            System.out.println(message);
        }
//        Map<String, Object> map = jsonToMap(message);
//        if (map.get("pid").equals("00000001")) {
//            System.out.println(message);
//        }
        try {
            List<Future<?>> futures = new ArrayList<>();
            wsServers.forEach(ws -> {
                threadPoolTaskExecutor.execute(() -> {
                Future<?> future = threadPoolTaskExecutor.submit(() -> {
                    Session session = ws.session;
                    if (session != null && session.isOpen()) {
                        Lock sessionLock = getSessionLock(session.getId());
                        sessionLock.lock();
                        try {
                            synchronized (session){
                                session.getAsyncRemote().sendText(message);
                                session.getBasicRemote().sendText(message);
                            }
                        } catch (Exception e) {
                            log.error("发送消息时出现异常: " + e.getMessage());
@@ -94,16 +93,27 @@
                        log.error("会话不存在或已关闭,无法发送消息");
                    }
                });
                futures.add(future);
            });
            //等待所有任务执行完成
            for (Future<?> future : futures) {
                try {
                    future.get();
                } catch (InterruptedException | ExecutionException e) {
                    log.error("发送消息时出现异常: " + e.getMessage());
                }
            }
        } catch (Exception e) {
            log.error("发送消息时出现异常: " + e.getMessage());
        }
    }
    public static Map<String, Object> jsonToMap(String json) {
        Gson gson = new Gson();
        Type type = new TypeToken<Map<String, Object>>() {
        }.getType();
        return gson.fromJson(json, type);
    }
//
//    public static Map<String, Object> jsonToMap(String json) {
//        Gson gson = new Gson();
//        Type type = new TypeToken<Map<String, Object>>() {
//        }.getType();
//        return gson.fromJson(json, type);
//    }
}