有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

javanio选择器和通道使用问题

我真的对java nio感到困惑

package org.eclipse.java.nio.selector.test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class MySelector {
    public static void main(String[] args) throws IOException {
        // Create selector
        Selector selector = null;
        selector = Selector.open();
        ////////////////////////////////////////////////////////////////////////
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress(
                "localhost", 4321));
        socketChannel.configureBlocking(false);
        socketChannel.register(selector, SelectionKey.OP_READ);
        /*
         * Let's begin select
         */
        while (true) {
            int readyChannels = selector.select();
            if (readyChannels == 0) continue;

            System.out.println("Hello, selector!");
            Set readyKeys = selector.selectedKeys();
            Iterator it = readyKeys.iterator();  
            while (it.hasNext()) {
                SelectionKey key = (SelectionKey )it.next();
                if (key.isReadable()) {
                    System.out.println("It's readable!");
                }
                it.remove();
            }
        }
    }
}

我希望选择器等待来自远程服务器的下一个输入事件,但在服务器回复任何单词后,它陷入了无限循环,为什么? 我真的不明白,“删除”不起作用? 我不想取消或关闭通道,我想保持连接,让客户端等待服务器的回复


共 (0) 个答案