Example usage for io.netty.channel ChannelOption SO_REUSEADDR

List of usage examples for io.netty.channel ChannelOption SO_REUSEADDR

Introduction

In this page you can find the example usage for io.netty.channel ChannelOption SO_REUSEADDR.

Prototype

ChannelOption SO_REUSEADDR

To view the source code for io.netty.channel ChannelOption SO_REUSEADDR.

Click Source Link

Usage

From source file:org.onosproject.openflow.controller.impl.Controller.java

License:Apache License

/**
 * Tell controller that we're ready to accept switches loop.
 *//*from ww  w.j  av a 2 s  . c o m*/
public void run() {

    try {
        final ServerBootstrap bootstrap = createServerBootStrap();
        bootstrap.option(ChannelOption.SO_REUSEADDR, true);
        bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
        bootstrap.childOption(ChannelOption.TCP_NODELAY, true);
        bootstrap.childOption(ChannelOption.SO_SNDBUF, Controller.SEND_BUFFER_SIZE);
        //            bootstrap.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK,
        //                                  new WriteBufferWaterMark(8 * 1024, 32 * 1024));

        bootstrap.childHandler(new OFChannelInitializer(this, null, sslContext));

        openFlowPorts.forEach(port -> {
            // TODO revisit if this is best way to listen to multiple ports
            cg.add(bootstrap.bind(port).syncUninterruptibly().channel());
            log.info("Listening for switch connections on {}", port);
        });

    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}

From source file:org.opencloudb.config.model.SystemConfig.java

License:Open Source License

public void setSocketParams(AbstractBootstrap<?, ?> bootstrap, boolean isFrontChannel) throws IOException {
    int sorcvbuf = 0;
    int sosndbuf = 0;
    int soNoDelay = 0;
    if (isFrontChannel) {
        sorcvbuf = getFrontsocketsorcvbuf();
        sosndbuf = getFrontsocketsosndbuf();
        soNoDelay = getFrontSocketNoDelay();
    } else {/*from   w  ww .  ja  va2 s. com*/
        sorcvbuf = getBacksocketsorcvbuf();
        sosndbuf = getBacksocketsosndbuf();
        soNoDelay = getBackSocketNoDelay();
    }

    bootstrap.option(ChannelOption.SO_RCVBUF, sorcvbuf);
    bootstrap.option(ChannelOption.SO_SNDBUF, sosndbuf);
    bootstrap.option(ChannelOption.TCP_NODELAY, soNoDelay == 1);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 1024 * 1024);
}

From source file:org.opendaylight.ocpjava.protocol.impl.core.TcpHandler.java

License:Open Source License

/**
 * Starts server on selected port.//from w ww.  ja  va  2  s. c o  m
 */
@Override
public void run() {
    /*
     * We generally do not perform IO-unrelated tasks, so we want to have
     * all outstanding tasks completed before the executing thread goes
     * back into select.
     *
     * Any other setting means netty will measure the time it spent selecting
     * and spend roughly proportional time executing tasks.
     */
    workerGroup.setIoRatio(100);

    final ChannelFuture f;
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(channelInitializer)
                .option(ChannelOption.SO_BACKLOG, 128).option(ChannelOption.SO_REUSEADDR, true)
                //modify to "false" for OCP health-check
                .childOption(ChannelOption.SO_KEEPALIVE, false).childOption(ChannelOption.TCP_NODELAY, true)
                .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, DEFAULT_WRITE_HIGH_WATERMARK * 1024)
                .childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, DEFAULT_WRITE_LOW_WATERMARK * 1024)
                .childOption(ChannelOption.WRITE_SPIN_COUNT, DEFAULT_WRITE_SPIN_COUNT);

        if (startupAddress != null) {
            f = b.bind(startupAddress.getHostAddress(), port).sync();
        } else {
            f = b.bind(port).sync();
        }
    } catch (InterruptedException e) {
        LOG.error("Interrupted while binding port {}", port, e);
        return;
    }

    try {
        InetSocketAddress isa = (InetSocketAddress) f.channel().localAddress();
        address = isa.getHostString();

        // Update port, as it may have been specified as 0
        this.port = isa.getPort();

        LOG.debug("address from tcphandler: {}", address);
        isOnlineFuture.set(true);
        LOG.info("RadioHead listener started and ready to accept incoming tcp/tls connections on port: {}",
                port);
        f.channel().closeFuture().sync();
    } catch (InterruptedException e) {
        LOG.error("Interrupted while waiting for port {} shutdown", port, e);
    } finally {
        shutdown();
    }
}

From source file:org.opendaylight.openflowjava.protocol.impl.core.TcpHandler.java

License:Open Source License

/**
 * Starts server on selected port.//  www  .  j  a  va 2s.  c o m
 */
@Override
public void run() {
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(channelInitializer)
                .option(ChannelOption.SO_BACKLOG, 128).option(ChannelOption.SO_REUSEADDR, true)
                .childOption(ChannelOption.SO_KEEPALIVE, true);

        ChannelFuture f;
        if (startupAddress != null) {
            f = b.bind(startupAddress.getHostAddress(), port).sync();
        } else {
            f = b.bind(port).sync();
        }

        InetSocketAddress isa = (InetSocketAddress) f.channel().localAddress();
        address = isa.getHostString();
        LOGGER.debug("address from tcphandler: " + address);
        port = isa.getPort();
        isOnlineFuture.set(true);
        LOGGER.info("Switch listener started and ready to accept incoming connections on port: " + port);
        f.channel().closeFuture().sync();
    } catch (InterruptedException ex) {
        LOGGER.error(ex.getMessage(), ex);
    } finally {
        shutdown();
    }
}

From source file:org.opendaylight.protocol.bgp.rib.impl.AbstractAddPathTest.java

License:Open Source License

private static ChannelFuture createClient(final BGPDispatcherImpl dispatcher,
        final InetSocketAddress remoteAddress, final BGPPeerRegistry registry,
        final InetSocketAddress localAddress, final BGPHandlerFactory hf) throws InterruptedException {
    final BGPClientSessionNegotiatorFactory snf = new BGPClientSessionNegotiatorFactory(registry);

    final Bootstrap bootstrap = dispatcher.createClientBootStrap(Optional.<KeyMapping>absent(),
            Epoll.isAvailable() ? new EpollEventLoopGroup() : new NioEventLoopGroup());
    bootstrap.localAddress(localAddress);
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override// w w  w  .  j  a va 2 s.  co  m
        protected void initChannel(final SocketChannel ch) throws Exception {
            ch.pipeline().addLast(hf.getDecoders());
            ch.pipeline().addLast("negotiator",
                    snf.getSessionNegotiator(ch, new DefaultPromise<BGPSessionImpl>(ch.eventLoop())));
            ch.pipeline().addLast(hf.getEncoders());
        }
    });
    return bootstrap.connect(remoteAddress).sync();
}

From source file:org.opendaylight.protocol.bgp.rib.impl.TestClientDispatcher.java

License:Open Source License

protected TestClientDispatcher(final EventLoopGroup bossGroup, final EventLoopGroup workerGroup,
        final MessageRegistry messageRegistry, final InetSocketAddress localAddress) {
    this.disp = new BGPDispatcherImpl(messageRegistry, bossGroup, workerGroup) {
        @Override/*from   w  w w . jav  a  2  s. co m*/
        protected Bootstrap createClientBootStrap(final Optional<KeyMapping> keys,
                final EventLoopGroup workerGroup) {
            final Bootstrap bootstrap = new Bootstrap();
            if (Epoll.isAvailable()) {
                bootstrap.channel(EpollSocketChannel.class);
            } else {
                bootstrap.channel(NioSocketChannel.class);
            }
            // Make sure we are doing round-robin processing
            bootstrap.option(ChannelOption.MAX_MESSAGES_PER_READ, 1);
            bootstrap.option(ChannelOption.SO_KEEPALIVE, Boolean.TRUE);

            if (bootstrap.group() == null) {
                bootstrap.group(workerGroup);
            }
            bootstrap.localAddress(localAddress);
            bootstrap.option(ChannelOption.SO_REUSEADDR, true);
            return bootstrap;
        }
    };
    this.hf = new BGPHandlerFactory(messageRegistry);
    this.localAddress = localAddress;
    this.defaultAddress = localAddress;
}

From source file:org.opendaylight.protocol.bmp.impl.app.BmpMonitorImplTest.java

License:Open Source License

private Channel connectTestClient(final String routerIp, final BmpMessageRegistry msgRegistry)
        throws InterruptedException {
    final BmpHandlerFactory hf = new BmpHandlerFactory(msgRegistry);
    final Bootstrap b = new Bootstrap();
    final EventLoopGroup workerGroup;
    if (Epoll.isAvailable()) {
        b.channel(EpollSocketChannel.class);
        workerGroup = new EpollEventLoopGroup();
    } else {//from   www  . j a  v a2 s .co  m
        b.channel(NioSocketChannel.class);
        workerGroup = new NioEventLoopGroup();
    }
    b.group(workerGroup);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(final SocketChannel ch) throws Exception {
            ch.pipeline().addLast(hf.getDecoders());
            ch.pipeline().addLast(hf.getEncoders());
        }
    });
    b.localAddress(new InetSocketAddress(routerIp, 0));
    b.option(ChannelOption.SO_REUSEADDR, true);
    final ChannelFuture future = b.connect(new InetSocketAddress(MONITOR_LOCAL_ADDRESS, MONITOR_LOCAL_PORT))
            .sync();
    waitFutureSuccess(future);
    return future.channel();
}

From source file:org.opendaylight.protocol.bmp.mock.BmpMockDispatcher.java

License:Open Source License

private Bootstrap createClientInstance(final SocketAddress localAddress) {
    final NioEventLoopGroup workergroup = new NioEventLoopGroup();
    final Bootstrap bootstrap = new Bootstrap();

    bootstrap.channel(NioSocketChannel.class);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT);
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    bootstrap.group(workergroup);//from  ww  w. java 2s .  co m

    bootstrap.handler(new ChannelInitializer<NioSocketChannel>() {
        @Override
        protected void initChannel(final NioSocketChannel ch) throws Exception {
            ch.pipeline().addLast(BmpMockDispatcher.this.sessionFactory.getSession(ch, null));
            ch.pipeline().addLast(BmpMockDispatcher.this.hf.getEncoders());
        }
    });
    bootstrap.localAddress(localAddress);
    return bootstrap;
}

From source file:org.opendaylight.protocol.pcep.pcc.mock.protocol.PCCDispatcherImpl.java

License:Open Source License

@Override
public Future<PCEPSession> createClient(@Nonnull final InetSocketAddress remoteAddress,
        @Nonnull final long reconnectTime, @Nonnull final PCEPSessionListenerFactory listenerFactory,
        @Nonnull final PCEPSessionNegotiatorFactory negotiatorFactory, @Nonnull final KeyMapping keys,
        @Nullable final InetSocketAddress localAddress, @Nonnull final BigInteger dbVersion) {
    final Bootstrap b = new Bootstrap();
    b.group(this.workerGroup);
    b.localAddress(localAddress);//from  w ww.jav a  2s .  c  o m
    final Optional<KeyMapping> optionalKey = Optional.fromNullable(keys);
    setChannelFactory(b, optionalKey);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.option(ChannelOption.SO_REUSEADDR, true);
    b.option(ChannelOption.MAX_MESSAGES_PER_READ, 1);
    final long retryTimer = reconnectTime == -1 ? 0 : reconnectTime;
    final PCCReconnectPromise promise = new PCCReconnectPromise(remoteAddress, (int) retryTimer,
            CONNECT_TIMEOUT, b);
    final ChannelInitializer<SocketChannel> channelInitializer = new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(final SocketChannel ch) throws Exception {
            ch.pipeline().addLast(PCCDispatcherImpl.this.factory.getDecoders());
            ch.pipeline().addLast("negotiator", negotiatorFactory.getSessionNegotiator(listenerFactory, ch,
                    promise, new PCCPeerProposal(dbVersion)));
            ch.pipeline().addLast(PCCDispatcherImpl.this.factory.getEncoders());
            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                @Override
                public void channelInactive(final ChannelHandlerContext ctx) throws Exception {
                    if (promise.isCancelled()) {
                        return;
                    }

                    if (!promise.isInitialConnectFinished()) {
                        LOG.debug("Connection to {} was dropped during negotiation, reattempting",
                                remoteAddress);
                        return;
                    }
                    LOG.debug("Reconnecting after connection to {} was dropped", remoteAddress);
                    PCCDispatcherImpl.this.createClient(remoteAddress, reconnectTime, listenerFactory,
                            negotiatorFactory, keys, localAddress, dbVersion);
                }
            });
        }
    };
    b.handler(channelInitializer);
    promise.connect();
    return promise;
}

From source file:org.proton.plug.test.minimalserver.MinimalServer.java

License:Apache License

public synchronized void start(String host, int port, final boolean sasl) throws Exception {
    this.host = host;
    this.port = port;
    this.sasl = sasl;

    if (channelClazz != null) {
        // Already started
        return;//  ww w. j  av  a  2s .c o  m
    }

    int threadsToUse = Runtime.getRuntime().availableProcessors() * 3;
    channelClazz = NioServerSocketChannel.class;
    eventLoopGroup = new NioEventLoopGroup(threadsToUse, new SimpleServerThreadFactory("simple-server", true,
            Thread.currentThread().getContextClassLoader()));

    bootstrap = new ServerBootstrap();
    bootstrap.group(eventLoopGroup);
    bootstrap.channel(channelClazz);

    ChannelInitializer<Channel> factory = new ChannelInitializer<Channel>() {
        @Override
        public void initChannel(Channel channel) throws Exception {
            ChannelPipeline pipeline = channel.pipeline();
            pipeline.addLast("amqp-handler", new ProtocolDecoder());
        }
    };
    bootstrap.childHandler(factory);

    bootstrap.option(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.SO_REUSEADDR, true)
            .childOption(ChannelOption.SO_KEEPALIVE, true).
            //       childOption(ChannelOption.AUTO_READ, false).
            childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

    channelGroup = new DefaultChannelGroup("activemq-accepted-channels", GlobalEventExecutor.INSTANCE);

    serverChannelGroup = new DefaultChannelGroup("activemq-acceptor-channels", GlobalEventExecutor.INSTANCE);

    SocketAddress address;
    address = new InetSocketAddress(host, port);
    Channel serverChannel = bootstrap.bind(address).syncUninterruptibly().channel();
    serverChannelGroup.add(serverChannel);

}