Java NIO 非阻塞:如何拒绝传入连接?

Mac*_*iej 5 java connection nio nonblocking

我正在尝试使用基于“Rox Java NIO 教程”中的 java NIO(非阻塞)的服务器端代码。有很多传入的套接字连接,我只想接受 100 个。因此,如果有 100 个活动连接,则应拒绝/拒绝新的连接。但如何做到这一点呢?只有方法 ServerSocketChannel.accept() 返回 SocketChannel 对象。使用该对象我可以调用 socketChannel.socket().close(),但连接已经打开。这是代码的一部分:

@Override
public void run() {
    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);
                } else if (key.isReadable()) {
                    this.read(key);
                } else if (key.isWritable()) {
                    this.write(key);
                }
            }
        } catch (Exception e) {
            logger.warn("Reading data", e);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

和accept()方法:

 private void accept(SelectionKey key) throws IOException {
    // For an accept to be pending the channel must be a server socket channel.
    ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();

    // Accept the connection and make it non-blocking        
    if (noOfConnections < MAX_CONNECTIONS) {
        SocketChannel socketChannel = serverSocketChannel.accept();
        Socket socket = socketChannel.socket();
        socket.setKeepAlive(true);
        socketChannel.configureBlocking(false);
        // Register the new SocketChannel with our Selector, indicating
        // we'd like to be notified when there's data waiting to be read
        socketChannel.register(this.selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);//listener for incoming data: READ from client, WRITE to client
        noOfConnections++;
        logger.info("Accepted: " + socket.getRemoteSocketAddress().toString());
    } else {

        // REJECT INCOMING CONNECTION, but how?

        logger.warn("Server is full: " + noOfConnections + " / " + MAX_CONNECTIONS);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果连接未被接受,则一遍又一遍地调用accept()方法。

感谢帮助!

use*_*421 2

没有办法实现这一点,但我怀疑这是否是您真正想要的,或者至少是您真正应该做的。

如果要停止接受连接,请将服务器套接字通道的选择键中的interestOps更改为0,并OP_ACCEPT在准备再次接受时将其更改回。在此期间,isAcceptable()永远不会成立,因此您描述的问题不会发生。

然而,这不会导致进一步的连接被拒绝:它只会将它们留在积压队列中,在我和 TCP 设计者看来,它们属于这些队列。如果积压队列已满,则会出现另一种失败行为:其在客户端中的影响取决于系统:连接拒绝和/或超时。