zhoushihao
2 天以前 4e3b8155722b66e25df3c6fd42cc586b68dea391
hangzhoumesParent/common/servicebase/src/main/java/com/mes/tools/WebSocketServer.java
@@ -22,12 +22,6 @@
    public static ConfigurableApplicationContext applicationContext;
    // 解决无法注入mapper问题 //使用方法
    // homeMapper=WebSocketServer.applicationContext.getBean(HomeMapper.class);
    public static void setApplicationContext(ConfigurableApplicationContext configurableApplicationContext) {
        WebSocketServer.applicationContext = configurableApplicationContext;
    }
    private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);
    private List<String> messages;
    /**
@@ -111,8 +105,6 @@
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("message", text);
        this.messages.add(text);
        this.sendMessage(jsonObject.toString()); // JSONUtil.toJsonStr(jsonObject)
    }
    @OnError
@@ -127,9 +119,32 @@
    public void sendMessage(String message) {
        try {
            // log.info("服务端给客户端[{}]发送消息{}", this.session.getId(), message);
            this.session.getBasicRemote().sendText(message);
            if(this.session.isOpen()){
                int maxChunkSize = 50000; // 定义最大的分块大小
                int length = message.length();
                if(length>50000){
                    int chunks = (int) Math.ceil((double) length / maxChunkSize);
                    //分块发送消息
                    for (int i = 0; i < chunks; i++) {
                        int startIndex = i * maxChunkSize;
                        int endIndex = Math.min(startIndex + maxChunkSize, length);
                        String chunk = message.substring(startIndex, endIndex);
                        // 判断是否是最后一块消息
                        boolean isLastChunk = (i == chunks - 1);
                        if(isLastChunk==true){
                            chunk+="<END>";
                        }
                        // 发送分块消息,并传递是否是最后一块消息的标识
                        this.session.getBasicRemote().sendText(chunk);
                    }
                }else{
                    this.session.getBasicRemote().sendText(message);
                }
            }
        } catch (Exception e) {
            log.error("服务端发送消息给客户端失败", e);
            log.error("发送消息给客户端失败:{}", e.getMessage(), e);
        }
    }