多线程应用程序

时间:2015-05-13 15:51:41

标签: java multithreading selector nio

我尝试制作多线程服务器应用程序,它可以与100个或更多客户端通信。为了避免套接字和并发编程,我使用了nio.Selector。它工作正常,但我不确定这是最好的解决方案。我该如何申请? 这是我的服务器部分:

    selector = Selector.open();
    channel = ServerSocketChannel.open();
    channel.configureBlocking(false);
    channel.register(selector, SelectionKey.OP_ACCEPT);
    channel.socket().bind(new InetSocketAddress(host, port));

        while (true) {
        try {
            if (selector.select() == 0) {
                continue;
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }

        Set<SelectionKey> keys = selector.selectedKeys();

        for (SelectionKey key : keys) {
            if (key.isValid()) {
                if (key.isAcceptable()) {
                    try {
                        registerChanell();
                    } catch (IOException e) {
                        System.out.println(e.getMessage());
                    }
                } else {
                    if (key.isReadable()) {
                        handleCommand(key);
                    }
                }
            } else {
                closeChanell(key);
            }
        }
        keys.clear();
    }

1 个答案:

答案 0 :(得分:1)

我不确定你为什么要这样做,为什么你不能简单地编写一个通用的servlet,你只需要覆盖抽象服务方法。搜索更多信息javax.servlet.GenericServlet

相关问题