package com.yushu.web.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;
import java.io.IOException;

/**
 * 简单的WebSocket测试服务器
 */
@ServerEndpoint("/ws/test")
@Component
public class SimpleWebSocketServer {
    
    private static final Logger log = LoggerFactory.getLogger(SimpleWebSocketServer.class);
    
    static {
        log.info("[WebSocket] SimpleWebSocketServer 类正在加载...");
    }
    
    @OnOpen
    public void onOpen(Session session) {
        log.info("[WebSocket] 测试连接建立: {}", session.getId());
        try {
            session.getBasicRemote().sendText("连接成功！");
        } catch (IOException e) {
            log.error("[WebSocket] 发送欢迎消息失败", e);
        }
    }
    
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("[WebSocket] 收到消息: {}", message);
        try {
            session.getBasicRemote().sendText("收到: " + message);
        } catch (IOException e) {
            log.error("[WebSocket] 发送响应失败", e);
        }
    }
    
    @OnClose
    public void onClose(Session session) {
        log.info("[WebSocket] 连接关闭: {}", session.getId());
    }
    
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("[WebSocket] 连接错误: {}", session.getId(), error);
    }
}
