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

The following examples show how to use java.nio.channels.ServerSocketChannel#setOption() . 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: ChannelListener.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Adds a server socket channel for listening to connections.
 *
 * @param nicIPAddress - if null binds to wildcard address
 * @param port - port to bind to
 * @param receiveBufferSize - size of OS receive buffer to request. If less
 * than 0 then will not be set and OS default will win.
 * @throws IOException if unable to add socket
 */
public void addServerSocket(final InetAddress nicIPAddress, final int port, final int receiveBufferSize)
        throws IOException {
    final ServerSocketChannel ssChannel = ServerSocketChannel.open();
    ssChannel.configureBlocking(false);
    if (receiveBufferSize > 0) {
        ssChannel.setOption(StandardSocketOptions.SO_RCVBUF, receiveBufferSize);
        final int actualReceiveBufSize = ssChannel.getOption(StandardSocketOptions.SO_RCVBUF);
        if (actualReceiveBufSize < receiveBufferSize) {
            LOGGER.warn(this + " attempted to set TCP Receive Buffer Size to "
                    + receiveBufferSize + " bytes but could only set to " + actualReceiveBufSize
                    + "bytes. You may want to consider changing the Operating System's "
                    + "maximum receive buffer");
        }
    }
    ssChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    ssChannel.bind(new InetSocketAddress(nicIPAddress, port));
    ssChannel.register(serverSocketSelector, SelectionKey.OP_ACCEPT);
}
 
Example 2
Source File: SocketChannelDispatcher.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void open(final InetAddress nicAddress, final int port, final int maxBufferSize) throws IOException {
    stopped = false;
    executor = Executors.newFixedThreadPool(maxConnections);

    final ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    serverSocketChannel.configureBlocking(false);
    if (maxBufferSize > 0) {
        serverSocketChannel.setOption(StandardSocketOptions.SO_RCVBUF, maxBufferSize);
        final int actualReceiveBufSize = serverSocketChannel.getOption(StandardSocketOptions.SO_RCVBUF);
        if (actualReceiveBufSize < maxBufferSize) {
            logger.warn("Attempted to set Socket Buffer Size to " + maxBufferSize + " bytes but could only set to "
                    + actualReceiveBufSize + "bytes. You may want to consider changing the Operating System's "
                    + "maximum receive buffer");
        }
    }

    serverSocketChannel.socket().bind(new InetSocketAddress(nicAddress, port));

    selector = Selector.open();
    serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
}
 
Example 3
Source File: StandardServerChannelFactory.java    From yajsync with GNU General Public License v3.0 6 votes vote down vote up
@Override
public ServerChannel open(InetAddress address, int port, int timeout) throws IOException
{
    ServerSocketChannel sock = ServerSocketChannel.open();
    try {
        if (_isReuseAddress) {
            sock.setOption(StandardSocketOptions.SO_REUSEADDR, true);
        }
        InetSocketAddress socketAddress =
            new InetSocketAddress(address, port);
        sock.bind(socketAddress);
        return new StandardServerChannel(sock, timeout);
    } catch (Throwable t) {
        try {
            if (sock.isOpen()) {
                sock.close();
            }
        } catch (Throwable tt) {
            t.addSuppressed(tt);
        }
        throw t;
    }
}
 
Example 4
Source File: ChannelListener.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Adds a server socket channel for listening to connections.
 *
 * @param nicIPAddress - if null binds to wildcard address
 * @param port - port to bind to
 * @param receiveBufferSize - size of OS receive buffer to request. If less
 * than 0 then will not be set and OS default will win.
 * @throws IOException if unable to add socket
 */
public void addServerSocket(final InetAddress nicIPAddress, final int port, final int receiveBufferSize)
        throws IOException {
    final ServerSocketChannel ssChannel = ServerSocketChannel.open();
    ssChannel.configureBlocking(false);
    if (receiveBufferSize > 0) {
        ssChannel.setOption(StandardSocketOptions.SO_RCVBUF, receiveBufferSize);
        final int actualReceiveBufSize = ssChannel.getOption(StandardSocketOptions.SO_RCVBUF);
        if (actualReceiveBufSize < receiveBufferSize) {
            LOGGER.warn(this + " attempted to set TCP Receive Buffer Size to "
                    + receiveBufferSize + " bytes but could only set to " + actualReceiveBufSize
                    + "bytes. You may want to consider changing the Operating System's "
                    + "maximum receive buffer");
        }
    }
    ssChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    ssChannel.bind(new InetSocketAddress(nicIPAddress, port));
    ssChannel.register(serverSocketSelector, SelectionKey.OP_ACCEPT);
}
 
Example 5
Source File: SocketChannelDispatcher.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void open(final InetAddress nicAddress, final int port, final int maxBufferSize) throws IOException {
    stopped = false;
    executor = Executors.newFixedThreadPool(maxConnections);

    final ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    serverSocketChannel.configureBlocking(false);
    if (maxBufferSize > 0) {
        serverSocketChannel.setOption(StandardSocketOptions.SO_RCVBUF, maxBufferSize);
        final int actualReceiveBufSize = serverSocketChannel.getOption(StandardSocketOptions.SO_RCVBUF);
        if (actualReceiveBufSize < maxBufferSize) {
            logger.warn("Attempted to set Socket Buffer Size to " + maxBufferSize + " bytes but could only set to "
                    + actualReceiveBufSize + "bytes. You may want to consider changing the Operating System's "
                    + "maximum receive buffer");
        }
    }

    serverSocketChannel.socket().bind(new InetSocketAddress(nicAddress, port));

    selector = Selector.open();
    serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
}
 
Example 6
Source File: NioSocketAcceptor.java    From jane with GNU Lesser General Public License v3.0 6 votes vote down vote up
private ServerSocketChannel open(InetSocketAddress localAddress) throws IOException {
	if (localAddress == null)
		return null;
	ServerSocketChannel channel = ServerSocketChannel.open();
	try {
		channel.configureBlocking(false);
		channel.setOption(StandardSocketOptions.SO_REUSEADDR, Boolean.valueOf(reuseAddress));
		DefaultSocketSessionConfig config = getSessionConfig();
		if (config.getSendBufferSize() >= 0)
			channel.setOption(StandardSocketOptions.SO_SNDBUF, config.getSendBufferSize());
		if (config.getReceiveBufferSize() >= 0)
			channel.setOption(StandardSocketOptions.SO_RCVBUF, config.getReceiveBufferSize());
		try {
			channel.bind(localAddress, backlog);
		} catch (IOException ioe) {
			close(channel);
			throw new IOException("error while binding on " + localAddress, ioe);
		}
		channel.register(selector, SelectionKey.OP_ACCEPT);
		return channel;
	} catch (Throwable e) {
		close(channel);
		throw e;
	}
}
 
Example 7
Source File: ServerSocketSettings.java    From datakernel with Apache License 2.0 5 votes vote down vote up
public void applySettings(@NotNull ServerSocketChannel channel) throws IOException {
	if (receiveBufferSize != 0) {
		channel.setOption(SO_RCVBUF, receiveBufferSize);
	}
	if (reuseAddress != DEF_BOOL) {
		channel.setOption(SO_REUSEADDR, reuseAddress != FALSE);
	}
}
 
Example 8
Source File: ServerSocketChannelReopenTest.java    From netcrusher-java with Apache License 2.0 4 votes vote down vote up
private void reopen(Selector selector) throws Exception {
    ServerSocketChannel channel = ServerSocketChannel.open();
    channel.configureBlocking(false);
    channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    channel.bind(new InetSocketAddress("127.0.0.1", 17777));

    // --- if channel is not registered with selector the following close() method works fine
    SelectionKey selectionKey = channel.register(selector, SelectionKey.OP_ACCEPT);

    // --- trying to cancel the registration in selector - doesn't help
    // selectionKey.cancel();
    // selector.wakeup();

    // --- trying to configure the socket as blocking - doesn't help
    // selectionKey.cancel();
    // channel.configureBlocking(true);

    // --- trying to register the channel in other selector - doesn't help
    // selectionKey.cancel();
    // Selector nullSelector = Selector.open();
    // channel.register(nullSelector, 0);
    // nullSelector.close();

    // --- it helps!!!
    // selectionKey.cancel();
    // selector.selectNow();

    channel.close();

    // PROBLEM: after close() has returned I still see this port is listening
    //
    //     C:\Dev>netstat -nao | grep 17777
    //     TCP    127.0.0.1:17777        0.0.0.0:0              LISTENING       xxxx
    //
    // so on the next bind I get an exception: java.net.BindException: Address already in use: bind

    // --- it helps!!!
    selector.selectNow();

    // --- it helps!!! but I don't want to because there could multiple server sockets on the same selector
    // selector.close();

    // --- trying to shake-up the selector - doesn't help
    // selector.wakeup();

    // --- trying to wait some time - doesn't help
    // Thread.sleep(10000);
}
 
Example 9
Source File: NioSslIntegrationTest.java    From Chronicle-Network with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldEncryptAndDecryptTraffic() throws Exception {
    final ExecutorService threadPool = Executors.newFixedThreadPool(2,
            new NamedThreadFactory("test"));

    final ServerSocketChannel serverChannel = ServerSocketChannel.open();
    serverChannel.bind(new InetSocketAddress("0.0.0.0", 13337));
    serverChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    serverChannel.configureBlocking(true);

    final SocketChannel channel = SocketChannel.open();
    channel.configureBlocking(false);
    channel.connect(new InetSocketAddress("127.0.0.1", serverChannel.socket().getLocalPort()));

    try {

        final Client client = new Client(channel);

        final StateMachineProcessor clientProcessor = new StateMachineProcessor(channel, false,
                SSLContextLoader.getInitialisedContext(), client);

        final SocketChannel serverConnection = serverChannel.accept();
        serverConnection.configureBlocking(false);

        final Server server = new Server(serverConnection);
        final StateMachineProcessor serverProcessor = new StateMachineProcessor(serverConnection, true,
                SSLContextLoader.getInitialisedContext(), server);

        while (!(channel.finishConnect() && serverConnection.finishConnect())) {
            Thread.yield();
        }

        if (SEND_DATA_BEFORE_SSL_HANDSHAKE) {
            testDataConnection(channel, serverConnection);
        }

        threadPool.submit(clientProcessor);
        threadPool.submit(serverProcessor);

        client.waitForResponse(10, TimeUnit.SECONDS);
        serverProcessor.stop();
        clientProcessor.stop();
    } finally {
        Closeable.closeQuietly(channel, serverChannel);
    }

    threadPool.shutdown();
    assertTrue(threadPool.awaitTermination(10, TimeUnit.SECONDS));
}