Java SocketChannel在其他线程上关闭

时间:2014-07-15 15:20:14

标签: java multithreading socketchannel

我有一个帖子,女巫正在测试一个socketchannel选择器。 如果连接了一个socketchannel并且可以读取,它应该启动一个消息处理程序线程,读取并处理该消息。 我需要启动处理程序线程,因为还有很多工作要做,而且需要时间来完成它们。

主线程:

    while (true) {
        try {
            // Wait for an event one of the registered channels
            this.selector.select();

            // Iterate over the set of keys for which events are available
            Iterator selectedKeys = this.selector.selectedKeys().iterator();
            while (selectedKeys.hasNext()) {
                SelectionKey key = (SelectionKey) selectedKeys.next();
                selectedKeys.remove();

                if (!key.isValid()) {
                    continue;
                }

                // Check what event is available and deal with it
                if (key.isAcceptable()) {
                    this.accept(key);
                }
                if (key.isReadable()) {
                    this.read(key);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            Thread.sleep(200);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }

读取功能:

    private void read(SelectionKey key) throws IOException {
        // For an accept to be pending the channel must be a server socket channel.
        SocketChannel clientSocketChanel = (SocketChannel) key.channel();
        WebCommandHandler commands = new WebCommandHandler(clientSocketChanel);
        if (clientSocketChanel.isConnected()) {
            Thread cThread = new Thread(commands);
            cThread.setName("Message handler");
            cThread.start();
        }
    }

问题是,当执行处理程序线程时,给定的socketchannel已经关闭。 如果我没有运行该线程,只有我调用run()方法,那么套接字不会关闭,所以我认为主线程迭代正在关闭给定的SocketChannel。有人可以帮我找出解决方法,如何保持SocketChannel打开,直到处理程序线程停止工作?

修改

可能我应该"取消注册"来自选择器的SocketChannel,在开始新线程之前...如何从Seelctor取消注册socketChannel?

1 个答案:

答案 0 :(得分:0)

好的,我找到了解决方案...... 因此,我们应该从Selector中取消注册SocketChannel ......这可以通过调用key.cancel()函数来实现。