并发测试下Java NIO的管道错误

时间:2014-02-09 05:04:34

标签: java concurrency webserver nio java-io

我现在正在使用Java NIO构建一个事件驱动的服务器

当我做ab -n 100 -c 100 localhost:8080/时,一切都很好。 但是当我ab -n 10000 -c 1000 localhost:8080/时,发生错误!!

代码的一部分:

resHeader.append("Host: MyServer" + CRLF);
resHeader.append("Connection: close" + CRLF + CRLF);
ByteBuffer temp = ByteBuffer.wrap(resHeader.toString().getBytes());--(ClientHandler.java:372)
while(temp.hasRemaining()) {
    client.write(temp);
}

客户的定义:client = (SocketChannel) key.channel();

java.io.IOException: Broken pipe
    at sun.nio.ch.FileDispatcher.write0(Native Method)
    at sun.nio.ch.SocketDispatcher.write(SocketDispatcher.java:29)
    at sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:69)
    at sun.nio.ch.IOUtil.write(IOUtil.java:40)
    at sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:336)
    at ClientHandler.sendResponse(ClientHandler.java:372)
    at ClientHandler.parseRequest(ClientHandler.java:218)
    at ClientHandler.writeKey(ClientHandler.java:136)
    at ClientHandler.execute(ClientHandler.java:51)
    at TcpServer.main(TcpServer.java:33)

错误发生后,我将其添加到代码中:

ByteBuffer temp = null;
try {
    temp = ByteBuffer.wrap(resHeader.toString().getBytes());
    while(temp.hasRemaining()) {
        client.write(temp);
    }
} catch (IOException e) {
    System.err.println("TEST: " + temp.hasRemaining());
    System.out.println("connect:" + client.isConnected()
    // TODO Auto-generated catch block
    e.printStackTrace();
}

当错误再次弹出时,它会打印"TEST: true""connect:true",这意味着它没有完成写入。为什么会这样?

另外,我使用了ab -c 1000 -n 10000 -r http://localhost:8080/

-r : Don't exit on socket receive errors.

    Concurrency Level:      1000
    Time taken for tests:   18.700 seconds
    Complete requests:      10000
    Failed requests:        1878

   (Connect: 0, Receive: 626, Length: 626, Exceptions: 626)

(PS:使用此-r我没有收到错误:java.io.IOException: Broken pipe

这是否提供了一些有用的信息?

1 个答案:

答案 0 :(得分:0)

'断管'意味着对等体提前关闭了连接。它可以在加载时由于各种原因而做到这一点,其中没有一个与你的代码有任何关系。