当客户端和服务器是同一台机器时,SocketChannel读取和写入异常

时间:2019-06-27 16:06:33

标签: java nio socketchannel

我的代码中有一个结构,可以将ByteBuffers读写到套接字通道。在while循环中,我调用了onRead和onWrite方法。当我运行代码时,会得到类似“ m; i1000; s1; t2000 ...”的输出。当本地地址和远程地址是不同的IP时,一切都很好。但是,当本地地址和远程地址的主机相同时,当while循环尝试从通道读取时,我在while循环的第二次迭代中遇到了异常。但是,即使我每次运行代码也不会发生这种情况,而几次运行都没有问题。

我试图用Thread.sleep暂停程序,以为它可能是由于同一主机上的操作速度很高而发生的。似乎对案件没有影响。

这是while循环:

Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator();
while (selectedKeys.hasNext()) {
    SelectionKey key = (SelectionKey) selectedKeys.next();
    selectedKeys.remove();

    if (key.isReadable()) {
        // Here the onRead method is called.
        // The first call has no problem 
        // but for the second iteration it throws an exception in the below code.
        if (!onRead(key)) {
            disconnect();
            continue;
        }
    }
}

这是我提到的代码:

private ByteBuffer in;
private SocketChannel channel;
in = ByteBuffer.allocateDirect(InputBufferSize); // InputBufferSize = 64*1024
in.order(ByteOrder.BIG_ENDIAN);
channel = SocketChannel.open();
channel.socket().setSoTimeout(ConnectTimeout); //ConnectTimeout = 5
channel.connect(activeAddr); // activeAddr = 127.0.0.1:29000
channel.configureBlocking(false);

private boolean onRead(SelectionKey key) throws IOException {
    int len = 0;
    try {
        // It tries to read ByteBuffer into len
        // The exception is thrown here.
        len = channel.read(in); 
    } catch (Exception e){
        System.err.println("Exception thrown!");
        // The variables have these values here:
        // in.remaining() = 65503
        // channel.isConnected() = true
        // channel.getLocalAddress() = 127.0.0.1:36000
        // channel.getRemoteAddress() = 127.0.0.1:29000
    }
    if (len <= 0 && in.remaining() < 1) {
        System.err.println("Read error");
        return false;
    }

    in.flip();

    if (!processMessages()) {
        return false;
    }
    in.compact();
    return true;
}

预期输出如下:

Connecting to /127.0.0.1:29000
Connected to /127.0.0.1:29000
Login accepted. Session 20190621  . Seqno 1
m;i202006;s1;t154237.183;Dt20190620;
m;i202006;s1;t184512.573;Dt20190621;
End of session
Finished.

抛出异常时的输出:

Connecting to /127.0.0.1:29000
Connected to /127.0.01:29000
Login accepted. Session 20190621  . Seqno 1
m;i202006;s1;t154237.183;Dt20190620;
Exception thrown!

您知道为什么在所述情况下可能会引发异常吗?

0 个答案:

没有答案