Java Code Examples for java.nio.channels.ServerSocketChannel#close()

The following examples show how to use java.nio.channels.ServerSocketChannel#close() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FIXInitiatorTest.java    From philadelphia with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws IOException {
    clock = new FixedClock();

    ServerSocketChannel acceptorServerChannel = ServerSocketChannel.open();
    acceptorServerChannel.bind(null);

    SocketChannel initiatorChannel = SocketChannel.open(acceptorServerChannel.getLocalAddress());
    initiatorChannel.configureBlocking(false);

    SocketChannel acceptorChannel = acceptorServerChannel.accept();
    acceptorChannel.configureBlocking(false);

    acceptorServerChannel.close();

    initiatorMessages = new FIXMessages();
    acceptorMessages  = new TestMessages();

    initiatorStatus = new FIXConnectionStatus();

    initiator = new FIXConnection(clock, initiatorChannel, initiatorConfig, initiatorMessages, initiatorStatus);
    acceptor  = new TestConnection(acceptorChannel, acceptorMessages);
}
 
Example 2
Source File: TestingQuorumPeerMain.java    From curator with Apache License 2.0 6 votes vote down vote up
@Override
public void kill()
{
    try
    {
        if ( quorumPeer != null )
        {
            Field               cnxnFactoryField = QuorumPeer.class.getDeclaredField("cnxnFactory");
            cnxnFactoryField.setAccessible(true);
            ServerCnxnFactory   cnxnFactory = (ServerCnxnFactory)cnxnFactoryField.get(quorumPeer);
            Compatibility.serverCnxnFactoryCloseAll(cnxnFactory);

            Field               ssField = cnxnFactory.getClass().getDeclaredField("ss");
            ssField.setAccessible(true);
            ServerSocketChannel ss = (ServerSocketChannel)ssField.get(cnxnFactory);
            ss.close();
        }
        close();
    }
    catch ( Exception e )
    {
        e.printStackTrace();
    }
}
 
Example 3
Source File: SocketChannelTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * @tests SocketChannel#write(ByteBuffer) after close
 */
public void test_socketChannel_write_close() throws Exception {
    // regression 4 for HARMONY-549
    ServerSocketChannel ssc = ServerSocketChannel.open();
    ssc.socket().bind(null);
    SocketChannel sc = SocketChannel.open();
    sc.connect(ssc.socket().getLocalSocketAddress());
    SocketChannel sock = ssc.accept();
    ByteBuffer buf = null;
    ssc.close();
    sc.close();
    try {
        sc.write(buf);
        fail("should throw NPE");
    } catch (NullPointerException expected) {
    }
    sock.close();
}
 
Example 4
Source File: TestingZooKeeperMain.java    From curator with Apache License 2.0 6 votes vote down vote up
@Override
public void kill()
{
    try
    {
        if ( cnxnFactory != null )
        {
            Compatibility.serverCnxnFactoryCloseAll(cnxnFactory);

            Field ssField = cnxnFactory.getClass().getDeclaredField("ss");
            ssField.setAccessible(true);
            ServerSocketChannel ss = (ServerSocketChannel)ssField.get(cnxnFactory);
            ss.close();
        }

        close();
    }
    catch ( Exception e )
    {
        e.printStackTrace();    // just ignore - this class is only for testing
    }
}
 
Example 5
Source File: SocketChannelTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * @tests SocketChannel#read(ByteBuffer[], int, int) when remote server
 *        closed
 */
public void test_socketChannel_read_ByteBufferII_remoteClosed()
        throws Exception {
    // regression 1 for HARMONY-549
    ServerSocketChannel ssc = ServerSocketChannel.open();
    ssc.socket().bind(null);
    SocketChannel sc = SocketChannel.open();
    sc.connect(ssc.socket().getLocalSocketAddress());
    ssc.accept().close();
    ByteBuffer[] buf = { ByteBuffer.allocate(10) };
    assertEquals(-1, sc.read(buf, 0, 1));
    ssc.close();
    sc.close();
}
 
Example 6
Source File: HttpClientTest.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
public void close() throws IOException {
	Thread thread = this.thread;
	if (thread != null) {
		thread.interrupt();
	}
	ServerSocketChannel server = this.server;
	if (server != null) {
		server.close();
	}
}
 
Example 7
Source File: SocketChannelTest.java    From kieker with Apache License 2.0 5 votes vote down vote up
@Test
public void reconnectShouldWork() throws Exception {
	final SocketAddress socketAddress = new InetSocketAddress(this.hostname, this.port);
	final int timeout = 1;

	final Socket socket = SocketChannel.open().socket();
	try {
		socket.connect(socketAddress, timeout);
	} catch (SocketTimeoutException | ConnectException e) { // NOPMD (empty catch block)
		// both of the exceptions indicate a connection timeout
		// => ignore to reconnect
	}

	// The connect from above throws an exception so that the socket is closed.
	// isClosed includes isConnected=false.
	assertThat(socket.isClosed(), is(true)); // NOPMD (JUnit message is not necessary)

	final ServerSocketChannel serverSocketChannel = ServerSocketChannel.open().bind(socketAddress);
	try {
		// start server in a non-blocking way
		serverSocketChannel.configureBlocking(false);
		serverSocketChannel.accept();

		// reconnect to the server (requires a new channel)
		final Socket anotherSocket = SocketChannel.open().socket();
		try {
			anotherSocket.connect(socketAddress);
		} finally {
			anotherSocket.close();
		}
	} finally {
		serverSocketChannel.close();
	}
}
 
Example 8
Source File: PrivilegedSocketOperationsBenchmark.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Benchmark
public ServerSocketChannel testWithoutSMNoPrivileged(final SecurityManagerEmpty sm) throws IOException {
    final ServerSocketChannel ssc = ServerSocketChannel.open();
    ssc.socket().bind(null);
    ssc.configureBlocking(false);
    ssc.accept();
    ssc.close();
    return ssc;
}
 
Example 9
Source File: ChannelOperationsHandlerTest.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
public void close() throws IOException {
	Thread thread = this.thread;
	if (thread != null) {
		thread.interrupt();
	}
	ServerSocketChannel server = this.server;
	if (server != null) {
		server.close();
	}
}
 
Example 10
Source File: SocketChannelTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * @tests java.nio.channels.SocketChannel#write(ByteBuffer[])
 */
public void test_write$LByteBuffer2() throws IOException {
    // Set-up
    ServerSocketChannel server = ServerSocketChannel.open();
    server.socket().bind(null);
    SocketChannel client = SocketChannel.open();
    client.connect(server.socket().getLocalSocketAddress());
    SocketChannel worker = server.accept();

    // Test overlapping buffers
    byte[] data = "Hello world!".getBytes("UTF-8");
    ByteBuffer[] buffers = new ByteBuffer[3];
    buffers[0] = ByteBuffer.wrap(data, 0, 6);
    buffers[1] = ByteBuffer.wrap(data, 6, data.length - 6);
    buffers[2] = ByteBuffer.wrap(data);

    // Write them out, read what we wrote and check it
    client.write(buffers);
    client.close();
    ByteBuffer readBuffer = ByteBuffer.allocate(1024);
    while (EOF != worker.read(readBuffer)) {}
    readBuffer.flip();
    Buffer expected = ByteBuffer.allocate(1024).put(data).put(data).flip();
    assertEquals(expected, readBuffer);

    // Tidy-up
    worker.close();
    server.close();
}
 
Example 11
Source File: ITCHSessionTest.java    From juncture with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    loginAccepted       = new ITCH.LoginAccepted();
    loginRejected       = new ITCH.LoginRejected();
    sequencedData       = new ITCH.SequencedData();
    errorNotification   = new ITCH.ErrorNotification();
    instrumentDirectory = new ITCH.InstrumentDirectory();

    loginRequest                 = new ITCH.LoginRequest();
    marketSnapshotRequest        = new ITCH.MarketSnapshotRequest();
    tickerSubscribeRequest       = new ITCH.TickerSubscribeRequest();
    tickerUnsubscribeRequest     = new ITCH.TickerUnsubscribeRequest();
    marketDataSubscribeRequest   = new ITCH.MarketDataSubscribeRequest();
    marketDataUnsubscribeRequest = new ITCH.MarketDataUnsubscribeRequest();

    clock = new FixedClock();

    ServerSocketChannel acceptor = ServerSocketChannel.open();
    acceptor.bind(null);

    SocketChannel clientChannel = SocketChannel.open(acceptor.getLocalAddress());

    SocketChannel serverChannel = acceptor.accept();
    acceptor.close();

    clientEvents = new ITCHClientEvents();
    serverEvents = new ITCHServerEvents();

    client = new ITCHClient(clock, clientChannel, RX_BUFFER_CAPACITY, clientEvents);
    server = new ITCHServer(clock, serverChannel, RX_BUFFER_CAPACITY, serverEvents);
}
 
Example 12
Source File: RacyDeregister.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    InetAddress addr = InetAddress.getByName(null);
    ServerSocketChannel sc = ServerSocketChannel.open();
    sc.socket().bind(new InetSocketAddress(addr, 0));

    SocketChannel.open(new InetSocketAddress(addr,
            sc.socket().getLocalPort()));

    SocketChannel accepted = sc.accept();
    accepted.configureBlocking(false);

    SocketChannel.open(new InetSocketAddress(addr,
            sc.socket().getLocalPort()));
    SocketChannel accepted2 = sc.accept();
    accepted2.configureBlocking(false);

    final Selector sel = Selector.open();
    SelectionKey key2 = accepted2.register(sel, SelectionKey.OP_READ);
    final SelectionKey[] key = new SelectionKey[]{
        accepted.register(sel, SelectionKey.OP_READ)};


    // thread that will be changing key[0].interestOps to OP_READ | OP_WRITE
    new Thread() {

        public void run() {
            try {
                for (int k = 0; k < 15; k++) {
                    for (int i = 0; i < 10000; i++) {
                        synchronized (notifyLock) {
                            synchronized (selectorLock) {
                                sel.wakeup();
                                key[0].interestOps(SelectionKey.OP_READ
                                        | SelectionKey.OP_WRITE);
                            }
                            notified = false;
                            long beginTime = System.currentTimeMillis();
                            while (true) {
                                notifyLock.wait(5000);
                                if (notified) {
                                    break;
                                }
                                long endTime = System.currentTimeMillis();
                                if (endTime - beginTime > 5000) {
                                    succTermination = false;
                                    // wake up main thread doing select()
                                    sel.wakeup();
                                    return;
                                }
                            }
                        }
                    }
                }
                succTermination = true;
                // wake up main thread doing select()
                sel.wakeup();
            } catch (Exception e) {
                System.out.println(e);
                succTermination = true;
                // wake up main thread doing select()
                sel.wakeup();
            }
        }
    }.start();

    // main thread will be doing registering/deregistering with the sel
    while (true) {
        sel.select();
        if (Boolean.TRUE.equals(succTermination)) {
            System.out.println("Test passed");
            sel.close();
            sc.close();
            break;
        } else if (Boolean.FALSE.equals(succTermination)) {
            System.out.println("Failed to pass the test");
            sel.close();
            sc.close();
            throw new RuntimeException("Failed to pass the test");
        }
        synchronized (selectorLock) {
        }
        if (sel.selectedKeys().contains(key[0]) && key[0].isWritable()) {
            synchronized (notifyLock) {
                notified = true;
                notifyLock.notify();
                key[0].cancel();
                sel.selectNow();
                key2 = accepted2.register(sel, SelectionKey.OP_READ);
                key[0] = accepted.register(sel, SelectionKey.OP_READ);
            }
        }
        key2.cancel();
        sel.selectedKeys().clear();
    }
}
 
Example 13
Source File: RacyDeregister.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    InetAddress addr = InetAddress.getByName(null);
    ServerSocketChannel sc = ServerSocketChannel.open();
    sc.socket().bind(new InetSocketAddress(addr, 0));

    SocketChannel.open(new InetSocketAddress(addr,
            sc.socket().getLocalPort()));

    SocketChannel accepted = sc.accept();
    accepted.configureBlocking(false);

    SocketChannel.open(new InetSocketAddress(addr,
            sc.socket().getLocalPort()));
    SocketChannel accepted2 = sc.accept();
    accepted2.configureBlocking(false);

    final Selector sel = Selector.open();
    SelectionKey key2 = accepted2.register(sel, SelectionKey.OP_READ);
    final SelectionKey[] key = new SelectionKey[]{
        accepted.register(sel, SelectionKey.OP_READ)};


    // thread that will be changing key[0].interestOps to OP_READ | OP_WRITE
    new Thread() {

        public void run() {
            try {
                for (int k = 0; k < 15; k++) {
                    for (int i = 0; i < 10000; i++) {
                        synchronized (notifyLock) {
                            synchronized (selectorLock) {
                                sel.wakeup();
                                key[0].interestOps(SelectionKey.OP_READ
                                        | SelectionKey.OP_WRITE);
                            }
                            notified = false;
                            long beginTime = System.currentTimeMillis();
                            while (true) {
                                notifyLock.wait(5000);
                                if (notified) {
                                    break;
                                }
                                long endTime = System.currentTimeMillis();
                                if (endTime - beginTime > 5000) {
                                    succTermination = false;
                                    // wake up main thread doing select()
                                    sel.wakeup();
                                    return;
                                }
                            }
                        }
                    }
                }
                succTermination = true;
                // wake up main thread doing select()
                sel.wakeup();
            } catch (Exception e) {
                System.out.println(e);
                succTermination = true;
                // wake up main thread doing select()
                sel.wakeup();
            }
        }
    }.start();

    // main thread will be doing registering/deregistering with the sel
    while (true) {
        sel.select();
        if (Boolean.TRUE.equals(succTermination)) {
            System.out.println("Test passed");
            sel.close();
            sc.close();
            break;
        } else if (Boolean.FALSE.equals(succTermination)) {
            System.out.println("Failed to pass the test");
            sel.close();
            sc.close();
            throw new RuntimeException("Failed to pass the test");
        }
        synchronized (selectorLock) {
        }
        if (sel.selectedKeys().contains(key[0]) && key[0].isWritable()) {
            synchronized (notifyLock) {
                notified = true;
                notifyLock.notify();
                key[0].cancel();
                sel.selectNow();
                key2 = accepted2.register(sel, SelectionKey.OP_READ);
                key[0] = accepted.register(sel, SelectionKey.OP_READ);
            }
        }
        key2.cancel();
        sel.selectedKeys().clear();
    }
}
 
Example 14
Source File: CloseAfterConnect.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    ServerSocketChannel ssc = ServerSocketChannel.open();
    ssc.socket().bind(new InetSocketAddress(0));

    InetAddress lh = InetAddress.getLocalHost();
    final SocketChannel sc = SocketChannel.open();
    final InetSocketAddress isa =
        new InetSocketAddress(lh, ssc.socket().getLocalPort());

    // establish connection in another thread
    Runnable connector =
        new Runnable() {
            public void run() {
                try {
                    sc.connect(isa);
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        };
    Thread thr = new Thread(connector);
    thr.start();

    // wait for connect to be established and for thread to
    // terminate
    do {
        try {
            thr.join();
        } catch (InterruptedException x) { }
    } while (thr.isAlive());

    // check connection is established
    if (!sc.isConnected()) {
        throw new RuntimeException("SocketChannel not connected");
    }

    // close channel - this triggered the bug as it attempted to signal
    // a thread that no longer exists
    sc.close();

    // clean-up
    ssc.accept().close();
    ssc.close();
}
 
Example 15
Source File: TcpClientTests.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
public void close() throws IOException {
	ServerSocketChannel server = this.server;
	if (server != null) {
		server.close();
	}
}
 
Example 16
Source File: RacyDeregister.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    InetAddress addr = InetAddress.getByName(null);
    ServerSocketChannel sc = ServerSocketChannel.open();
    sc.socket().bind(new InetSocketAddress(addr, 0));

    SocketChannel.open(new InetSocketAddress(addr,
            sc.socket().getLocalPort()));

    SocketChannel accepted = sc.accept();
    accepted.configureBlocking(false);

    SocketChannel.open(new InetSocketAddress(addr,
            sc.socket().getLocalPort()));
    SocketChannel accepted2 = sc.accept();
    accepted2.configureBlocking(false);

    final Selector sel = Selector.open();
    SelectionKey key2 = accepted2.register(sel, SelectionKey.OP_READ);
    final SelectionKey[] key = new SelectionKey[]{
        accepted.register(sel, SelectionKey.OP_READ)};


    // thread that will be changing key[0].interestOps to OP_READ | OP_WRITE
    new Thread() {

        public void run() {
            try {
                for (int k = 0; k < 15; k++) {
                    for (int i = 0; i < 10000; i++) {
                        synchronized (notifyLock) {
                            synchronized (selectorLock) {
                                sel.wakeup();
                                key[0].interestOps(SelectionKey.OP_READ
                                        | SelectionKey.OP_WRITE);
                            }
                            notified = false;
                            long beginTime = System.currentTimeMillis();
                            while (true) {
                                notifyLock.wait(5000);
                                if (notified) {
                                    break;
                                }
                                long endTime = System.currentTimeMillis();
                                if (endTime - beginTime > 5000) {
                                    succTermination = false;
                                    // wake up main thread doing select()
                                    sel.wakeup();
                                    return;
                                }
                            }
                        }
                    }
                }
                succTermination = true;
                // wake up main thread doing select()
                sel.wakeup();
            } catch (Exception e) {
                System.out.println(e);
                succTermination = true;
                // wake up main thread doing select()
                sel.wakeup();
            }
        }
    }.start();

    // main thread will be doing registering/deregistering with the sel
    while (true) {
        sel.select();
        if (Boolean.TRUE.equals(succTermination)) {
            System.out.println("Test passed");
            sel.close();
            sc.close();
            break;
        } else if (Boolean.FALSE.equals(succTermination)) {
            System.out.println("Failed to pass the test");
            sel.close();
            sc.close();
            throw new RuntimeException("Failed to pass the test");
        }
        synchronized (selectorLock) {
        }
        if (sel.selectedKeys().contains(key[0]) && key[0].isWritable()) {
            synchronized (notifyLock) {
                notified = true;
                notifyLock.notify();
                key[0].cancel();
                sel.selectNow();
                key2 = accepted2.register(sel, SelectionKey.OP_READ);
                key[0] = accepted.register(sel, SelectionKey.OP_READ);
            }
        }
        key2.cancel();
        sel.selectedKeys().clear();
    }
}
 
Example 17
Source File: CloseAfterConnect.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    ServerSocketChannel ssc = ServerSocketChannel.open();
    ssc.socket().bind(new InetSocketAddress(0));

    InetAddress lh = InetAddress.getLocalHost();
    final SocketChannel sc = SocketChannel.open();
    final InetSocketAddress isa =
        new InetSocketAddress(lh, ssc.socket().getLocalPort());

    // establish connection in another thread
    Runnable connector =
        new Runnable() {
            public void run() {
                try {
                    sc.connect(isa);
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        };
    Thread thr = new Thread(connector);
    thr.start();

    // wait for connect to be established and for thread to
    // terminate
    do {
        try {
            thr.join();
        } catch (InterruptedException x) { }
    } while (thr.isAlive());

    // check connection is established
    if (!sc.isConnected()) {
        throw new RuntimeException("SocketChannel not connected");
    }

    // close channel - this triggered the bug as it attempted to signal
    // a thread that no longer exists
    sc.close();

    // clean-up
    ssc.accept().close();
    ssc.close();
}
 
Example 18
Source File: RacyDeregister.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    InetAddress addr = InetAddress.getByName(null);
    ServerSocketChannel sc = ServerSocketChannel.open();
    sc.socket().bind(new InetSocketAddress(addr, 0));

    SocketChannel.open(new InetSocketAddress(addr,
            sc.socket().getLocalPort()));

    SocketChannel accepted = sc.accept();
    accepted.configureBlocking(false);

    SocketChannel.open(new InetSocketAddress(addr,
            sc.socket().getLocalPort()));
    SocketChannel accepted2 = sc.accept();
    accepted2.configureBlocking(false);

    final Selector sel = Selector.open();
    SelectionKey key2 = accepted2.register(sel, SelectionKey.OP_READ);
    final SelectionKey[] key = new SelectionKey[]{
        accepted.register(sel, SelectionKey.OP_READ)};


    // thread that will be changing key[0].interestOps to OP_READ | OP_WRITE
    new Thread() {

        public void run() {
            try {
                for (int k = 0; k < 15; k++) {
                    for (int i = 0; i < 10000; i++) {
                        synchronized (notifyLock) {
                            synchronized (selectorLock) {
                                sel.wakeup();
                                key[0].interestOps(SelectionKey.OP_READ
                                        | SelectionKey.OP_WRITE);
                            }
                            notified = false;
                            long beginTime = System.currentTimeMillis();
                            while (true) {
                                notifyLock.wait(5000);
                                if (notified) {
                                    break;
                                }
                                long endTime = System.currentTimeMillis();
                                if (endTime - beginTime > 5000) {
                                    succTermination = false;
                                    // wake up main thread doing select()
                                    sel.wakeup();
                                    return;
                                }
                            }
                        }
                    }
                }
                succTermination = true;
                // wake up main thread doing select()
                sel.wakeup();
            } catch (Exception e) {
                System.out.println(e);
                succTermination = true;
                // wake up main thread doing select()
                sel.wakeup();
            }
        }
    }.start();

    // main thread will be doing registering/deregistering with the sel
    while (true) {
        sel.select();
        if (Boolean.TRUE.equals(succTermination)) {
            System.out.println("Test passed");
            sel.close();
            sc.close();
            break;
        } else if (Boolean.FALSE.equals(succTermination)) {
            System.out.println("Failed to pass the test");
            sel.close();
            sc.close();
            throw new RuntimeException("Failed to pass the test");
        }
        synchronized (selectorLock) {
        }
        if (sel.selectedKeys().contains(key[0]) && key[0].isWritable()) {
            synchronized (notifyLock) {
                notified = true;
                notifyLock.notify();
                key[0].cancel();
                sel.selectNow();
                key2 = accepted2.register(sel, SelectionKey.OP_READ);
                key[0] = accepted.register(sel, SelectionKey.OP_READ);
            }
        }
        key2.cancel();
        sel.selectedKeys().clear();
    }
}
 
Example 19
Source File: NetworkAdminImpl.java    From BiglyBT with GNU General Public License v2.0 2 votes vote down vote up
@Override
public int
getBindablePort(
	int	prefer_port )

	throws IOException
{
	final int tries = 1024;

	Random random = new Random();

	for ( int i=1;i<=tries;i++ ){

		int port;

		if ( i == 1 && prefer_port != 0 ){

			port = prefer_port;

		}else{

			port = i==tries?0:random.nextInt(20000) + 40000;
		}

		ServerSocketChannel ssc = null;

		try{
			ssc = ServerSocketChannel.open();

			ssc.socket().setReuseAddress( true );

			bind( ssc, null, port );

			port = ssc.socket().getLocalPort();

			ssc.close();

			return( port );

		}catch( Throwable e ){

			if ( ssc != null ){

				try{
					ssc.close();

				}catch( Throwable f ){

					Debug.printStackTrace(e);
				}

				ssc = null;
			}
		}
	}

	throw( new IOException( "No bindable ports found" ));
}
 
Example 20
Source File: NetworkAdmin.java    From TorrentEngine with GNU General Public License v3.0 2 votes vote down vote up
public int
getBindablePort(
	int	prefer_port )

	throws IOException
{
	final int tries = 1024;

	Random random = new Random();

	for ( int i=1;i<=tries;i++ ){

		int port;

		if ( i == 1 && prefer_port != 0 ){

			port = prefer_port;

		}else{

			port = i==tries?0:random.nextInt(20000) + 40000;
		}

		ServerSocketChannel ssc = null;

		try{
			ssc = ServerSocketChannel.open();

			ssc.socket().setReuseAddress( true );

			bind( ssc, null, port );

			port = ssc.socket().getLocalPort();

			ssc.close();

			return( port );

		}catch( Throwable e ){

			if ( ssc != null ){

				try{
					ssc.close();

				}catch( Throwable f ){

					Debug.printStackTrace(e);
				}

				ssc = null;
			}
		}
	}

	throw( new IOException( "No bindable ports found" ));
}