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.apache.zookeeper.server.NettyServerCnxnFactory.java

License:Apache License

NettyServerCnxnFactory() {
    x509Util = new ClientX509Util();

    EventLoopGroup bossGroup = NettyUtils.newNioOrEpollEventLoopGroup();
    EventLoopGroup workerGroup = NettyUtils.newNioOrEpollEventLoopGroup();
    ServerBootstrap bootstrap = new ServerBootstrap().group(bossGroup, workerGroup)
            .channel(NettyUtils.nioOrEpollServerSocketChannel())
            // parent channel options
            .option(ChannelOption.SO_REUSEADDR, true)
            // child channels options
            .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_LINGER, -1)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override//from w  w w.  ja va  2 s.  co  m
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    if (secure) {
                        initSSL(pipeline);
                    }
                    pipeline.addLast("servercnxnfactory", channelHandler);
                }
            });
    this.bootstrap = configureBootstrapAllocator(bootstrap);
    this.bootstrap.validate();
}

From source file:org.asciidoctor.maven.http.AsciidoctorHttpServer.java

License:Apache License

public void start() {
    final AtomicInteger threadId = new AtomicInteger(1);
    workerGroup = new NioEventLoopGroup(THREAD_NUMBER, new ThreadFactory() {
        @Override// w ww . j  av  a 2 s  . c  om
        public Thread newThread(final Runnable r) {
            final Thread t = new Thread(r, THREAD_PREFIX + threadId.getAndIncrement());
            if (t.getPriority() != Thread.NORM_PRIORITY) {
                t.setPriority(Thread.NORM_PRIORITY);
            }
            if (t.isDaemon()) {
                t.setDaemon(false);
            }
            return t;
        }
    });

    try {
        bootstrap = new ServerBootstrap();
        bootstrap.option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.SO_SNDBUF, 1024)
                .option(ChannelOption.TCP_NODELAY, true).group(workerGroup)
                .channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(final SocketChannel ch) throws Exception {
                        ch.pipeline().addLast("decoder", new HttpRequestDecoder())
                                .addLast("aggregator", new HttpObjectAggregator(Integer.MAX_VALUE))
                                .addLast("encoder", new HttpResponseEncoder())
                                .addLast("chunked-writer", new ChunkedWriteHandler())
                                .addLast("asciidoctor", new AsciidoctorHandler(workDir, defaultPage));
                    }
                }).bind(port).addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(final ChannelFuture future) throws Exception {
                        if (!future.isSuccess()) {
                            logger.error("Can't start HTTP server");
                        } else {
                            logger.info(String.format("Server started on http://%s:%s", HOST, port));
                        }
                    }
                }).sync();
    } catch (final InterruptedException e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:org.asynchttpclient.netty.channel.ChannelManager.java

License:Open Source License

private Bootstrap newBootstrap(ChannelFactory<? extends Channel> channelFactory, EventLoopGroup eventLoopGroup,
        AsyncHttpClientConfig config) {/*from  w  w  w .j  a  v  a2 s.c  o  m*/
    @SuppressWarnings("deprecation")
    Bootstrap bootstrap = new Bootstrap().channelFactory(channelFactory).group(eventLoopGroup)//
            // default to PooledByteBufAllocator
            .option(ChannelOption.ALLOCATOR,
                    config.isUsePooledMemory() ? PooledByteBufAllocator.DEFAULT
                            : UnpooledByteBufAllocator.DEFAULT)//
            .option(ChannelOption.TCP_NODELAY, config.isTcpNoDelay())//
            .option(ChannelOption.SO_REUSEADDR, config.isSoReuseAddress())//
            .option(ChannelOption.AUTO_CLOSE, false);

    if (config.getConnectTimeout() > 0) {
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getConnectTimeout());
    }

    if (config.getSoLinger() >= 0) {
        bootstrap.option(ChannelOption.SO_LINGER, config.getSoLinger());
    }

    if (config.getSoSndBuf() >= 0) {
        bootstrap.option(ChannelOption.SO_SNDBUF, config.getSoSndBuf());
    }

    if (config.getSoRcvBuf() >= 0) {
        bootstrap.option(ChannelOption.SO_RCVBUF, config.getSoRcvBuf());
    }

    for (Entry<ChannelOption<Object>, Object> entry : config.getChannelOptions().entrySet()) {
        bootstrap.option(entry.getKey(), entry.getValue());
    }

    return bootstrap;
}

From source file:org.ballerinalang.test.agent.server.WebServer.java

License:Open Source License

/**
 * Initializes the server, socket, and channel.
 *
 * @param loopGroup The event loop group.
 * @param serverChannelClass The socket channel class.
 * @throws InterruptedException on interruption.
 *///ww  w .  j a v  a2s . c om
private void start(final EventLoopGroup loopGroup, final Class<? extends ServerChannel> serverChannelClass)
        throws InterruptedException {
    try {
        final InetSocketAddress inet = new InetSocketAddress(host, port);

        final ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.option(ChannelOption.SO_BACKLOG, 1024);
        serverBootstrap.option(ChannelOption.SO_REUSEADDR, true);
        serverBootstrap.group(loopGroup).channel(serverChannelClass).childHandler(new WebServerInitializer());
        serverBootstrap.option(ChannelOption.MAX_MESSAGES_PER_READ, Integer.MAX_VALUE);
        serverBootstrap.childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(true));
        serverBootstrap.childOption(ChannelOption.SO_REUSEADDR, true);
        serverBootstrap.childOption(ChannelOption.MAX_MESSAGES_PER_READ, Integer.MAX_VALUE);

        final Channel ch = serverBootstrap.bind(inet).sync().channel();
        ch.closeFuture().sync();
    } finally {
        loopGroup.shutdownGracefully().sync();
    }
}

From source file:org.codice.alliance.video.stream.mpegts.UdpStreamMonitor.java

License:Open Source License

private void runMulticastServer(Bootstrap bootstrap, NetworkInterface networkInterface,
        InetAddress inetAddress) {

    bootstrap.group(eventLoopGroup).channelFactory(() -> new NioDatagramChannel(InternetProtocolFamily.IPv4))
            .handler(new Pipeline(udpStreamProcessor)).localAddress(inetAddress, monitoredPort)
            .option(ChannelOption.IP_MULTICAST_IF, networkInterface).option(ChannelOption.SO_REUSEADDR, true);

    try {//from   w w  w .jav a 2s  .c  o  m
        channelFuture = bootstrap.bind(monitoredPort).sync();
        NioDatagramChannel ch = (NioDatagramChannel) channelFuture.channel();

        ch.joinGroup(new InetSocketAddress(monitoredAddress, monitoredPort), networkInterface).sync();
    } catch (InterruptedException e) {
        LOGGER.debug("interrupted while waiting for shutdown", e);
    }
}

From source file:org.eclipse.neoscada.protocol.iec60870.server.Server.java

License:Open Source License

public Server(final SocketAddress address, final ProtocolOptions options, final List<ServerModule> modules) {
    this.options = options;

    this.manager = new MessageManager(this.options);

    this.bossGroup = new NioEventLoopGroup();
    this.workerGroup = new NioEventLoopGroup();
    this.bootstrap = new ServerBootstrap();
    this.bootstrap.group(this.bossGroup, this.workerGroup);
    this.bootstrap.channel(NioServerSocketChannel.class);
    this.bootstrap.option(ChannelOption.SO_BACKLOG, 5);
    this.bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    this.bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

        @Override//from   w w w.j  a v a  2s  . c om
        protected void initChannel(final SocketChannel ch) throws Exception {
            handleInitChannel(ch);
        }
    });

    this.modules = modules.toArray(new ServerModule[modules.size()]);
    for (final ServerModule module : modules) {
        module.initializeServer(this, this.manager);
    }

    this.channel = this.bootstrap.bind(address).channel();
}

From source file:org.eclipse.scada.protocol.iec60870.server.Server.java

License:Open Source License

public Server(final short port, final ProtocolOptions options, final List<ServerModule> modules) {
    this.options = options;

    this.manager = new MessageManager(this.options);

    this.bossGroup = new NioEventLoopGroup();
    this.workerGroup = new NioEventLoopGroup();
    this.bootstrap = new ServerBootstrap();
    this.bootstrap.group(this.bossGroup, this.workerGroup);
    this.bootstrap.channel(NioServerSocketChannel.class);
    this.bootstrap.option(ChannelOption.SO_BACKLOG, 5);
    this.bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    this.bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

        @Override/*from  ww  w .j av a2  s  . c  om*/
        protected void initChannel(final SocketChannel ch) throws Exception {
            handleInitChannel(ch);
        }
    });

    this.modules = modules.toArray(new ServerModule[modules.size()]);
    for (final ServerModule module : modules) {
        module.initializeServer(this, this.manager);
    }

    this.channel = this.bootstrap.bind(port).channel();
}

From source file:org.eclipse.scada.protocol.relp.service.Receiver.java

License:Open Source License

public Receiver(final ReceiverHandlerFactory factory, final SocketAddress addr) {
    this.factory = factory;

    this.bossGroup = new NioEventLoopGroup();
    this.workerGroup = new NioEventLoopGroup();
    this.bootstrap = new ServerBootstrap();
    this.bootstrap.group(this.bossGroup, this.workerGroup);
    this.bootstrap.channel(NioServerSocketChannel.class);
    this.bootstrap.option(ChannelOption.SO_BACKLOG, 5);
    this.bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    this.bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

        @Override//from   w  w  w  .ja  va2s . c o m
        protected void initChannel(final SocketChannel ch) throws Exception {
            handleInitChannel(ch);
        }
    });

    this.channel = this.bootstrap.bind(addr).channel();

    logger.info("Receiver running ...");
}

From source file:org.elasticsearch.hadoop.http.netty4.Netty4HttpServerTransport.java

License:Apache License

@Override
protected void doStart() {
    this.serverOpenChannels = new Netty4OpenChannelsHandler(logger);

    serverBootstrap = new ServerBootstrap();
    if (blockingServer) {
        serverBootstrap/*from  w w w .ja  va 2 s  .  c o  m*/
                .group(new OioEventLoopGroup(workerCount, daemonThreadFactory(settings, "http_server_worker")));
        serverBootstrap.channel(OioServerSocketChannel.class);
    } else {
        serverBootstrap
                .group(new NioEventLoopGroup(workerCount, daemonThreadFactory(settings, "http_server_worker")));
        serverBootstrap.channel(NioServerSocketChannel.class);
    }

    serverBootstrap.childHandler(configureServerChannelHandler());

    serverBootstrap.childOption(ChannelOption.TCP_NODELAY, SETTING_HTTP_TCP_NO_DELAY.get(settings));
    serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, SETTING_HTTP_TCP_KEEP_ALIVE.get(settings));

    final ByteSizeValue tcpSendBufferSize = SETTING_HTTP_TCP_SEND_BUFFER_SIZE.get(settings);
    if (tcpSendBufferSize.bytes() > 0) {
        serverBootstrap.childOption(ChannelOption.SO_SNDBUF, Math.toIntExact(tcpSendBufferSize.bytes()));
    }

    final ByteSizeValue tcpReceiveBufferSize = SETTING_HTTP_TCP_RECEIVE_BUFFER_SIZE.get(settings);
    if (tcpReceiveBufferSize.bytes() > 0) {
        serverBootstrap.childOption(ChannelOption.SO_RCVBUF, Math.toIntExact(tcpReceiveBufferSize.bytes()));
    }

    serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator);
    serverBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator);

    final boolean reuseAddress = SETTING_HTTP_TCP_REUSE_ADDRESS.get(settings);
    serverBootstrap.option(ChannelOption.SO_REUSEADDR, reuseAddress);
    serverBootstrap.childOption(ChannelOption.SO_REUSEADDR, reuseAddress);

    this.boundAddress = createBoundHttpAddress();
}

From source file:org.elasticsearch.hadoop.transport.netty4.Netty4Transport.java

License:Apache License

private Bootstrap createBootstrap() {
    final Bootstrap bootstrap = new Bootstrap();
    if (TCP_BLOCKING_CLIENT.get(settings)) {
        bootstrap.group(new OioEventLoopGroup(1,
                daemonThreadFactory(settings, TRANSPORT_CLIENT_WORKER_THREAD_NAME_PREFIX)));
        bootstrap.channel(OioSocketChannel.class);
    } else {//from   ww w.  java2 s.com
        bootstrap.group(new NioEventLoopGroup(workerCount,
                daemonThreadFactory(settings, TRANSPORT_CLIENT_BOSS_THREAD_NAME_PREFIX)));
        bootstrap.channel(NioSocketChannel.class);
    }

    bootstrap.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("size", new Netty4SizeHeaderFrameDecoder());
            // using a dot as a prefix means this cannot come from any settings parsed
            ch.pipeline().addLast("dispatcher",
                    new Netty4MessageChannelHandler(Netty4Transport.this, ".client"));
        }

    });

    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, Math.toIntExact(connectTimeout.millis()));
    bootstrap.option(ChannelOption.TCP_NODELAY, TCP_NO_DELAY.get(settings));
    bootstrap.option(ChannelOption.SO_KEEPALIVE, TCP_KEEP_ALIVE.get(settings));

    final ByteSizeValue tcpSendBufferSize = TCP_SEND_BUFFER_SIZE.get(settings);
    if (tcpSendBufferSize.bytes() > 0) {
        bootstrap.option(ChannelOption.SO_SNDBUF, Math.toIntExact(tcpSendBufferSize.bytes()));
    }

    final ByteSizeValue tcpReceiveBufferSize = TCP_RECEIVE_BUFFER_SIZE.get(settings);
    if (tcpReceiveBufferSize.bytes() > 0) {
        bootstrap.option(ChannelOption.SO_RCVBUF, Math.toIntExact(tcpReceiveBufferSize.bytes()));
    }

    bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator);

    final boolean reuseAddress = TCP_REUSE_ADDRESS.get(settings);
    bootstrap.option(ChannelOption.SO_REUSEADDR, reuseAddress);

    bootstrap.validate();

    return bootstrap;
}