无法在NIO中获得输出

时间:2015-09-11 14:02:46

标签: java nio

我希望该程序在我输入内容时给我一个回音,我没有收到任何错误但它没有工作,它连接正常但我没有收到任何回复我输入服务器

private static Selector selector;

public static void main(String[] args) throws IOException {
    selector = Selector.open();
    ServerSocketChannel ssc = ServerSocketChannel.open();
    ssc.bind(new InetSocketAddress("localhost", 8080));
    ssc.configureBlocking(false);
    ssc.register(selector, SelectionKey.OP_ACCEPT);
    while (true) {
        selector.select();
        for (Iterator<SelectionKey> it = selector.selectedKeys().iterator(); it.hasNext();) {
            SelectionKey key = it.next();
            it.remove();
            if (key.isAcceptable())
                acceptRead(key);
            else if (key.isWritable())
                write(key);
        }
    }
}

private static void acceptRead(SelectionKey key) throws IOException {
    ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
    SocketChannel sc = ssc.accept();
    System.out.println("Connected with " + sc);
    sc.configureBlocking(false);
    SelectionKey key2 = sc.register(selector, SelectionKey.OP_WRITE);
    ByteBuffer buf = ByteBuffer.allocate(32);
    sc.read(buf);
    buf.flip();
    key2.attach(buf);
}

private static void write(SelectionKey key) throws IOException {
    SocketChannel sc = (SocketChannel) key.channel();
    ByteBuffer buf = (ByteBuffer) key.attachment();
    sc.write(buf);
}

}

1 个答案:

答案 0 :(得分:0)

这里的代码很奇怪。

  • 如果密钥可以接受,您应该在频道上拨打accept()
  • 如果密钥可读,您应该在频道上致电read()
  • 如果您从read()获得-1,则必须关闭该频道。
  • 写完后你必须compact()缓冲区,你肯定想再次为OP_READ注册频道吗?