0

我想在 java ee 中使用 java nio。但我不知道如何正确地做到这一点。我需要在服务器部署 java.nio.selector 后始终监听端口并处理套接字连接。我试着在那里做:

@Singleton
@Lock(LockType.READ)
public class TaskManager {

    private static final int LISTENINGPORT;

    static {
        LISTENINGPORT = ConfigurationSettings.getConfigureSettings().getListeningPort();
    }

    private ArrayList<ServerCalculationInfo> serverList;

    public TaskManager() {
        serverList = new ArrayList<ServerCalculationInfo>();
        select();
    }

    @Asynchronous
    public void select() {
        try {
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            Selector selector = Selector.open();
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.socket().bind(new InetSocketAddress(LISTENINGPORT));
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

            while (true) {
                try {
                    selector.select();
                } catch (IOException ex) {
                    Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
                    break;
                }
                Iterator it = selector.selectedKeys().iterator();
                while (it.hasNext()) {
                    SelectionKey selKey = (SelectionKey) it.next();
                    it.remove();
                    try {
                        processSelectionKey(serverSocketChannel, selKey);
                    } catch (IOException e) {
                        serverList.remove(serverCalculationInfo);
                    }
                }
            }

        } catch (IOException e) {
            Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, e);
        } catch (Exception e) {
            Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, e);
        }
    }
}

它不能正常工作。只有在重新启动 Glassfish 后,该进程才会在部署和重新部署应用程序期间挂起。我该怎么做呢?

4

1 回答 1

1

如果从@PostConstructor 调用@Asynchronous 方法,它可以正常工作:

@PostConstruct
public void postTaskManager() {
    serverList = new ArrayList<ServerCalculationInfo>();
    select();
}

而不是从构造函数调用它。但是类必须没有 @Startup 注释。

于 2012-10-28T06:32:29.820 回答