package com.wsm.admin.init;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

public class StartupUdpEvent implements ApplicationListener<ContextRefreshedEvent> {

    private static final Logger log = LoggerFactory.getLogger(StartupUdpEvent.class);

    private static ApplicationContext context;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        try {
            context = contextRefreshedEvent.getApplicationContext();

            log.warn("启动UDP线程，接收UDP消息，端口：2000");
            //接收UDP消息并保存至redis中
            UdpServer udpServer = (UdpServer)StartupUdpEvent.getBean(UdpServer.class);
            udpServer.run(2000);

            log.warn("启动TCP线程，接收TCP消息，端口：2020");
            TcpServer tcpServer = (TcpServer)StartupUdpEvent.getBean(TcpServer.class);
            tcpServer.startSocketServer(2020);

        } catch (Exception e) {
            log.error("Exception", e);
        }
    }

    public static Object getBean(Class beanName) {
        return context != null ? context.getBean(beanName) : null;
    }
}
