Java NIO 重定向连接

Java NIO Redirect connection

我正在尝试使用 nio 将连接重定向到另一台服务器, 这是我的代码,我认为问题出在 ByteBuffer.rewind() 因为这段代码以一种奇怪的方式重定向了数据。

public static void main(String[] args) throws Exception {

    ServerSocketChannel proxyServer = ServerSocketChannel.open();

    while (!Thread.interrupted()) {

        SocketChannel clientChannel = proxyServer.accept();
        clientChannel.configureBlocking(false);

        ByteBuffer uploadBuffer = ByteBuffer.allocate(1024 * 1024 * 5);
        ByteBuffer downloadBuffer = ByteBuffer.allocate(1024 * 1024 * 5);

        try {
            SocketChannel serverChannel = SocketChannel.open();
            serverChannel.connect(
                new InetSocketAddress(
                    "another server"
                    , 80
                )
            );

            while (!Thread.interrupted()) {

                // Client -> Server
                if (clientChannel.read(uploadBuffer) < 0) {
                    throw new EOFException();
                }

                uploadBuffer.rewind(); // <- maybe is this the error
                while (uploadBuffer.hasRemaining()) {
                    serverChannel.write(uploadBuffer);
                }

                // Server -> Client
                if (serverChannel.read(downloadBuffer) < 0) {
                    throw new EOFException();
                }

                downloadBuffer.rewind(); // <- maybe is this?
                while (downloadBuffer.hasRemaining()) {
                    clientChannel.write(downloadBuffer);
                }

                // Buffer reset
                downloadBuffer.clear();
                uploadBuffer.clear();
            }

        } catch (Exception exception) {
            clientChannel.close();
        }
    }
    proxyServer.close();
}

也许我必须使用翻转?

SocketChannel.read returns 接收到的字节数。无法保证该方法已填满 ByteBuffer。

您正在检查返回的计数是否为负数,但随后将其丢弃。您需要做的是注意 ByteBuffer 的 position after each read. As you suspected, the flip() 方法会为您处理。典型的用法是将一些字节读入 ByteBuffer,然后翻转该缓冲区,以便其他代码可以读取它。

所以,是的,将您的每个 rewind() 调用更改为 flip() 应该可以解决您的问题。