使用java选择器的无限循环

时间:2011-02-14 09:18:09

标签: java selector nio

我是Java的新手,现在我对java nio选择器感到困惑,下面是java网络程序第3版的代码,

package org.eclipse.java.socket.samples;

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

public class ChargenServer {
    public static int DEFAULT_PORT = 4321;
    public static void main(String[] args) {
        int port;
        try {
            port = Integer.parseInt(args[0]);
        }
        catch (Exception ex) {
            port = DEFAULT_PORT;
        }
        System.out.println("Listening for connections on port " + port);
        byte[] rotation = new byte[95 * 2];
        for (byte i = ' '; i <= '~'; i++) {
            rotation[i - ' '] = i;
            rotation[i + 95 - ' '] = i;
        }
        ServerSocketChannel serverChannel;
        Selector selector;
        try {
            serverChannel = ServerSocketChannel.open();
            ServerSocket ss = serverChannel.socket();
            InetSocketAddress address = new InetSocketAddress(port);
            ss.bind(address);
            serverChannel.configureBlocking(false);
            selector = Selector.open();
            serverChannel.register(selector, SelectionKey.OP_ACCEPT);
        }
        catch (IOException ex) {
            ex.printStackTrace();
            return;
        }
        while (true) {
            try {
                selector.select();
            }
            catch (IOException ex) {
                ex.printStackTrace();
                break;
            }            
            Set<SelectionKey> readyKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = readyKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey key = (SelectionKey) iterator.next();
                iterator.remove();
                try {
                    if (key.isAcceptable()) {
                        ServerSocketChannel server = (ServerSocketChannel) key
                                .channel();
                        SocketChannel client = server.accept();
                        System.out
                                .println("Accepted connection from " + client);
                        client.configureBlocking(false);
                        SelectionKey key2 = client.register(selector,
                                SelectionKey.
                                OP_WRITE);
                        ByteBuffer buffer = ByteBuffer.allocate(74);
                        buffer.put(rotation, 0, 72);
                        buffer.put((byte) '\r');
                        buffer.put((byte) '\n');
                        buffer.flip();
                        key2.attach(buffer);
                    }
                    else if (key.isWritable()) {
                        SocketChannel client = (SocketChannel) key.channel();
                        ByteBuffer buffer = (ByteBuffer) key.attachment();
                        if (!buffer.hasRemaining()) {
                            // Refill the buffer with the next line
                            buffer.rewind();
                            // Get the old first character
                            int first = buffer.get();
                            // Get ready to change the data in the buffer
                            buffer.rewind();
                            // Find the new first characters position in
                            // rotation
                            int position = first - ' ' + 1;
                            // copy the data from rotation into the buffer
                            buffer.put(rotation, position, 72);
                            // Store a line break at the end of the buffer
                            buffer.put((byte) '\r');
                            buffer.put((byte) '\n');
                            // Prepare the buffer for writing
                            buffer.flip();
                            buffer.compact();
                        }
                        client.write(buffer);
                    }
                }
                catch (IOException ex) {
                    key.cancel();
                    try {
                        key.channel().close();
                    }
                    catch (IOException cex) {
                    }
                }
            }
        }
    }
}

服务器非常简单,获得连接,然后回复客户端的串行字母, 但是当我在我的Ubuntu10.10上用

运行它时

Java版“1.6.0_20”

OpenJDK运行时环境(IcedTea6 1.9.4)(6b20-1.9.4-0ubuntu1)

OpenJDK Server VM(build 19.0-b09,混合模式)

我有一个无限循环,我真的不知道为什么,请帮帮我!

谢谢大家,但我仍然对选择器感到困惑,现在让我们更容易让我感到困惑,看看代码:

package org.eclipse.java.socket.selector;

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 SocketSelector {
    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_CONNECT);
        /*
         * Let's begin select
         */
        while (true) {
            selector.select();
            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();
            }
        }
    }
}

在我的理解中,“selector.select()”等待来自远程服务器的输入事件,然后it.remove()删除此事件,因此选择器开始等待来自远程服务器的新事件,因此客户端可以获得来自带有选择器的服务器的数据连续,但结果一次又一次地循环,选择器对服务器的数据毫无意义, 为什么? 我的代码有什么问题吗?

2 个答案:

答案 0 :(得分:1)

一旦你写完了你想要的一切(即,当out-buffer为空时),你应该删除OP_WRITE兴趣标志。

答案 1 :(得分:1)

三个是代码的多个问题,包括。不关闭选择器。

如果写入操作无法写入整个缓冲区,则需要仅注册OP_WRITE ,否则注销。看interestedOps()

通常,您需要OP_READ才能从该频道中读取。 最后总是在stackoverflow之前检查http://bugs.sun.com(这是我跟踪的一个错误)。建议:不要使用相同的选择器接受/写入。

http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4919127

欢呼声