Java NIO重定向连接

时间:2015-05-24 17:40:55

标签: java networking nio

我试图用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();
}

也许我必须使用翻转?

1 个答案:

答案 0 :(得分:0)

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

您正在检查返回的计数是否为负数,但是您将其丢弃。你需要做的是在每次阅读后注意ByteBuffer的position。如您所料,flip()方法会为您处理。一个典型的用法是将一些字节读入ByteBuffer,然后翻转该缓冲区,以便其它代码可以读取它。

所以,是的,将rewind()每个flip()来电更改为 while True: name =(input('enter')) l.append (name) break if choice == 'l': print (l) 可以解决您的问题。