package com.pdaaphm.webSocket.service.impl;

import com.pdaaphm.webSocket.config.WebSocketServer;
import com.pdaaphm.webSocket.service.IWebSocketService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description WebSocketServiceImpl
 * @Author WGK
 * @Date 2023/10/18 17:57
 */
@Slf4j
@Service
public class WebSocketServiceImpl implements IWebSocketService {
    @Autowired
    public WebSocketServer webSocketServer;

    public void sendMessage(String taskId, String logMessage) {
        try {
            ConcurrentHashMap<String, WebSocketServer> map = webSocketServer.getWebSocketMap();
            WebSocketServer server = map.get(taskId);
            if (server != null) {
                server.sendMessage(logMessage);
            } else {
                log.warn("客户端已退出");
            }
        } catch (IOException e) {
            log.error("向客户端发送消息时出现异常，异常原因:{}", e.getMessage(), e);
        }
    }
}
