publicstaticvoid main(String[] args) throws Exception { // establish loopback connection
AsynchronousServerSocketChannel listener =
AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(0)); int port = ((InetSocketAddress)(listener.getLocalAddress())).getPort();
InetSocketAddress isa = new InetSocketAddress(InetAddress.getLocalHost(), port);
AsynchronousSocketChannel ch1 = AsynchronousSocketChannel.open();
ch1.connect(isa).get();
AsynchronousSocketChannel ch2 = listener.accept().get();
// start thread to write to stream
Writer writer = new Writer(Channels.newOutputStream(ch1)); Thread writerThread = newThread(writer);
writerThread.start();
// start thread to read from stream
Reader reader = new Reader(Channels.newInputStream(ch2)); Thread readerThread = newThread(reader);
readerThread.start();
// wait for threads to complete
writerThread.join();
readerThread.join();
// shutdown listener
listener.close();
// check that reader received what we expected if (reader.total() != writer.total()) thrownew RuntimeException("Unexpected number of bytes read"); if (reader.hash() != writer.hash()) thrownew RuntimeException("Hash incorrect for bytes read");
// channels should be closed if (ch1.isOpen() || ch2.isOpen()) thrownew RuntimeException("Channels should be closed");
}
publicvoid run() { try { int n; do { // random offset/len byte[] buf = newbyte[128 + rand.nextInt(128)]; int len, off; if (rand.nextBoolean()) {
len = buf.length;
off = 0;
n = in.read(buf);
} else {
len = 1 + rand.nextInt(64);
off = rand.nextInt(64);
n = in.read(buf, off, len);
} if (n > len) thrownew RuntimeException("Too many bytes read"); if (n > 0) {
total += n; for (int i=0; i<n; i++) { int value = buf[off + i];
hash = hash ^ value;
}
}
} while (n > 0);
in.close();
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.