Path: blob/master/test/jdk/com/sun/nio/sctp/SctpServerChannel/NonBlockingAccept.java
41155 views
/*1* Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/* @test24* @bug 492764025* @summary Tests the SCTP protocol implementation26* @author chegar27*/2829import java.net.InetSocketAddress;30import java.net.SocketAddress;31import java.io.IOException;32import java.util.HashSet;33import java.util.Iterator;34import java.util.Set;35import java.util.concurrent.CountDownLatch;36import java.nio.channels.AlreadyConnectedException;37import java.nio.channels.Selector;38import java.nio.channels.SelectionKey;39import com.sun.nio.sctp.SctpChannel;40import com.sun.nio.sctp.SctpServerChannel;41import static java.lang.System.out;42import static java.lang.System.err;4344public class NonBlockingAccept {45static CountDownLatch acceptLatch = new CountDownLatch(1);46static final int SEL_TIMEOUT = 10000;47static final int NUM_TEST_CONNECTIONS = 10;4849void test(String[] args) {50SocketAddress address = null;51NonblockingServer server;5253if (!Util.isSCTPSupported()) {54out.println("SCTP protocol is not supported");55out.println("Test cannot be run");56return;57}5859if (args.length == 2) {60/* requested to connecct to a specific address */61try {62int port = Integer.valueOf(args[1]);63address = new InetSocketAddress(args[0], port);64} catch (NumberFormatException nfe) {65err.println(nfe);66}67} else {68/* start server on local machine, default */69try {70server = new NonblockingServer();71server.start();72address = server.address();73debug("Server started and listening on " + address);74} catch (IOException ioe) {75ioe.printStackTrace();76return;77}78}7980doClient(address);81}8283void doClient(SocketAddress peerAddress) {84Set<SctpChannel> channels = new HashSet<SctpChannel>(NUM_TEST_CONNECTIONS);8586try {87for (int i=0; i<NUM_TEST_CONNECTIONS;) {88debug("connecting " + ++i);89channels.add(SctpChannel.open(peerAddress, 0, 0));90sleep(100);91}9293/* don't close the channels until they have been accepted */94acceptLatch.await();9596for(SctpChannel sc: channels)97sc.close();98} catch (IOException ioe) {99unexpected(ioe);100} catch (InterruptedException ie) {101unexpected(ie);102}103}104105class NonblockingServer implements Runnable106{107final InetSocketAddress serverAddr;108private SctpServerChannel ssc;109private Thread serverThread;110111public NonblockingServer() throws IOException {112ssc = SctpServerChannel.open().bind(null);113java.util.Set<SocketAddress> addrs = ssc.getAllLocalAddresses();114if (addrs.isEmpty())115debug("addrs should not be empty");116117serverAddr = (InetSocketAddress) addrs.iterator().next();118}119120void start() {121serverThread = new Thread(this, "NonblockingServer-" +122serverAddr.getPort());123serverThread.start();124}125126InetSocketAddress address () {127return serverAddr;128}129130@Override131public void run() {132Selector acceptSelector = null;133SelectionKey acceptKey = null;134135try {136acceptSelector = Selector.open();137ssc.configureBlocking(false);138check(ssc.isBlocking() == false, "Should be in non-blocking mode");139acceptKey = ssc.register(acceptSelector, SelectionKey.OP_ACCEPT);140141int connectionsAccepted = 0;142while (connectionsAccepted < NUM_TEST_CONNECTIONS) {143int keysAdded = acceptSelector.select(SEL_TIMEOUT);144if (keysAdded > 0) {145Set<SelectionKey> keys = acceptSelector.selectedKeys();146Iterator<SelectionKey> i = keys.iterator();147while(i.hasNext()) {148SelectionKey sk = i.next();149i.remove();150SctpServerChannel nextReady =151(SctpServerChannel)sk.channel();152check(nextReady.equals(ssc),153"channels should be equal");154check(sk.isAcceptable(),155"key should be acceptable");156check(!sk.isReadable(),157"key should not be readable");158check(!sk.isWritable(),159"key should not be writable");160check(!sk.isConnectable(),161"key should not be connectable");162SctpChannel acceptsc = nextReady.accept();163connectionsAccepted++;164debug("Accepted " + connectionsAccepted + " connections");165check(acceptsc != null,166"Accepted channel should not be null");167if (acceptsc != null) {168checkAcceptedChannel(acceptsc);169acceptsc.close();170}171} /* while */172} /* if */173} /* while */174} catch (IOException ioe) {175ioe.printStackTrace();176} finally {177acceptLatch.countDown();178if (acceptKey != null) acceptKey.cancel();179try { if (acceptSelector != null) acceptSelector.close(); }180catch (IOException ioe) { unexpected(ioe); }181try { if (ssc != null) ssc.close(); }182catch (IOException ioe) { unexpected(ioe); }183}184}185}186187void checkAcceptedChannel(SctpChannel sc) {188try {189debug("Checking accepted SctpChannel");190check(sc.association() != null,191"accepted channel should have an association");192check(!(sc.getRemoteAddresses().isEmpty()),193"accepted channel should be connected");194check(!(sc.isConnectionPending()),195"accepted channel should not have a connection pending");196check(sc.isBlocking(),197"accepted channel should be blocking");198try { sc.connect(new TestSocketAddress()); fail(); }199catch (AlreadyConnectedException unused) { pass(); }200try { sc.bind(new TestSocketAddress()); fail(); }201catch (AlreadyConnectedException unused) { pass(); }202} catch (IOException unused) { fail(); }203}204205static class TestSocketAddress extends SocketAddress {}206207//--------------------- Infrastructure ---------------------------208boolean debug = true;209volatile int passed = 0, failed = 0;210void pass() {passed++;}211void fail() {failed++; Thread.dumpStack();}212void fail(String msg) {err.println(msg); fail();}213void unexpected(Throwable t) {failed++; t.printStackTrace();}214void check(boolean cond) {if (cond) pass(); else fail();}215void check(boolean cond, String failMessage) {if (cond) pass(); else fail(failMessage);}216void debug(String message) {if(debug) { out.println(message); } }217void sleep(long millis) { try { Thread.currentThread().sleep(millis); }218catch(InterruptedException ie) { unexpected(ie); }}219public static void main(String[] args) throws Throwable {220Class<?> k = new Object(){}.getClass().getEnclosingClass();221try {k.getMethod("instanceMain",String[].class)222.invoke( k.newInstance(), (Object) args);}223catch (Throwable e) {throw e.getCause();}}224public void instanceMain(String[] args) throws Throwable {225try {test(args);} catch (Throwable t) {unexpected(t);}226out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);227if (failed > 0) throw new AssertionError("Some tests failed");}228229}230231232