package com.ecep.contract.service; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import com.ecep.contract.handler.MessageNotitfication; import com.ecep.contract.handler.WebSocketServerHandler; import com.fasterxml.jackson.databind.ObjectMapper; /** * WebSocket消息服务 * 提供向客户端发送WebSocket消息的功能 */ @Service public class WebSocketService { private static final Logger logger = Logger.getLogger(WebSocketService.class.getName()); private final WebSocketServerHandler webSocketHandler; @Autowired private ObjectMapper objectMapper; public WebSocketService(WebSocketServerHandler webSocketHandler) { this.webSocketHandler = webSocketHandler; } /** * 向所有连接的客户端广播消息 * * @param message 要广播的消息内容 */ public void broadcastMessage(String message) { try { TextMessage textMessage = new TextMessage(message); webSocketHandler.broadcast(textMessage); logger.info("广播消息: " + message); } catch (Exception e) { logger.log(Level.SEVERE, "广播消息失败: " + e.getMessage(), e); } } /** * 向特定会话发送消息 * * @param session WebSocket会话 * @param message 要发送的消息内容 */ public void sendMessage(WebSocketSession session, String message) { try { if (session != null && session.isOpen()) { session.sendMessage(new TextMessage(message)); logger.info("向会话发送消息: " + session.getId() + ", 消息: " + message); } } catch (IOException e) { logger.log(Level.SEVERE, "向会话发送消息失败: " + session.getId() + ", 原因: " + e.getMessage(), e); } } /** * 获取当前活跃的WebSocket会话数量 * * @return 活跃会话数 */ public int getActiveSessionCount() { return webSocketHandler.getActiveSessionCount(); } /** * 发送系统通知 * * @param notification 通知内容 */ public void sendSystemNotification(String notification) { MessageNotitfication messageNotitfication = new MessageNotitfication(); messageNotitfication.setType("notification"); messageNotitfication.setContent(notification); try { String jsonMessage = objectMapper.writeValueAsString(messageNotitfication); broadcastMessage(jsonMessage); } catch (Exception e) { logger.log(Level.SEVERE, "发送系统通知失败: " + e.getMessage(), e); } } /** * 发送业务数据更新通知 * * @param dataType 数据类型 * @param operation 操作类型(create, update, delete) * @param id 数据ID */ public void sendDataUpdate(String dataType, String operation, String id) { String message = String.format( "{\"type\":\"data_update\",\"dataType\":\"%s\",\"operation\":\"%s\",\"id\":\"%s\"}", escapeJson(dataType), escapeJson(operation), escapeJson(id)); broadcastMessage(message); } /** * 转义JSON字符串中的特殊字符 * * @param text 要转义的文本 * @return 转义后的文本 */ private String escapeJson(String text) { if (text == null) { return ""; } return text .replace("\\", "\\\\") .replace("\"", "\\\"") .replace("\b", "\\b") .replace("\f", "\\f") .replace("\n", "\\n") .replace("\r", "\\r") .replace("\t", "\\t"); } }