【问题标题】:Java SocketChannel closed on other threadJava SocketChannel 在其他线程上关闭
【发布时间】:2014-07-15 15:20:14
【问题描述】:

我有一个线程,女巫正在测试一个套接字通道选择器。 如果套接字通道已连接并且可以读取,它应该启动一个消息处理线程,在该线程中读取和处理消息。 我需要启动处理程序线程,因为有很多事情要做,并且需要时间来完成它们。

主线程:

    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?

【问题讨论】:

    标签: java multithreading socketchannel


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-07
      • 2012-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-05
      • 1970-01-01
      相关资源
      最近更新 更多