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:io.jsync.net.impl.TCPSSLHelper.java

License:Open Source License

public void applyConnectionOptions(ServerBootstrap bootstrap) {
    bootstrap.childOption(ChannelOption.TCP_NODELAY, tcpNoDelay);
    if (tcpSendBufferSize != -1) {
        bootstrap.childOption(ChannelOption.SO_SNDBUF, tcpSendBufferSize);
    }/*from w w w. ja v a 2  s.  co  m*/
    if (tcpReceiveBufferSize != -1) {
        bootstrap.childOption(ChannelOption.SO_RCVBUF, tcpReceiveBufferSize);
        bootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR,
                new FixedRecvByteBufAllocator(tcpReceiveBufferSize));
    }

    // TODO this may not be needed
    if (soLinger != -1) {
        bootstrap.option(ChannelOption.SO_LINGER, soLinger);
    }
    if (trafficClass != -1) {
        bootstrap.childOption(ChannelOption.IP_TOS, trafficClass);
    }
    bootstrap.childOption(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);

    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, tcpKeepAlive);
    bootstrap.option(ChannelOption.SO_REUSEADDR, reuseAddress);
    bootstrap.option(ChannelOption.SO_BACKLOG, acceptBackLog);
}

From source file:io.maelstorm.server.ServerInit.java

License:Open Source License

public void start(String configFile, RequestHandler handler) throws Exception {
    LOG.info("Starting.");
    AppendableCharSequenceAddon.configure();
    try {//from w w w. ja v a2 s  . c om
        System.in.close(); // Release a FD we don't need.
    } catch (Exception e) {
        LOG.warn("Failed to close stdin", e);
    }
    Properties prop = getProperties(configFile);
    requestDistributor = handler;
    requestDistributor.setInitializer(this);
    String os = System.getProperty("os.name").toLowerCase(Locale.UK).trim();
    if (os.startsWith("linux")) {
        bossGroup = (null == bossGroup) ? new EpollEventLoopGroup(1) : bossGroup;
        workerGroup = (null == workerGroup) ? new EpollEventLoopGroup(NUM_WORKER_THREADS) : workerGroup;
    } else {
        bossGroup = (null == bossGroup) ? new NioEventLoopGroup(1) : bossGroup;
        workerGroup = (null == workerGroup) ? new NioEventLoopGroup(NUM_WORKER_THREADS) : workerGroup;
    }

    String[] servers = prop.getProperty("servers").split(",");
    for (String server : servers) {

        try {
            controller = new ServerBootstrap();
            controller.group(bossGroup, workerGroup);
            if (os.startsWith("linux")) {
                controller.channel(EpollServerSocketChannel.class);
                controller.option(EpollChannelOption.TCP_CORK, true);
            } else {
                controller.channel(NioServerSocketChannel.class);
            }
            controller.childHandler(new PipelineFactory(handler, getPipelineConfig(prop, server)));
            controller.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            controller.option(ChannelOption.RCVBUF_ALLOCATOR, AdaptiveRecvByteBufAllocator.DEFAULT);
            controller.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
                    getInt(prop, server, "connectTimeoutMillis"));
            controller.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 64 * 1024);
            controller.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 1 * 1024);
            controller.option(ChannelOption.SO_KEEPALIVE, getBoolean(prop, server, "SOKeepalive"));
            controller.option(ChannelOption.SO_REUSEADDR, true);
            controller.option(ChannelOption.TCP_NODELAY, true);
            controller.option(ChannelOption.SO_LINGER, 0);
            controller.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            controller.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 64 * 1024);
            controller.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 10);
            controller.childOption(ChannelOption.SO_KEEPALIVE, true);
            controller.childOption(ChannelOption.SO_REUSEADDR, true);
            controller.childOption(ChannelOption.TCP_NODELAY, true);
            controller.childOption(ChannelOption.SO_LINGER, 0);
            controller.childOption(ChannelOption.SO_RCVBUF, 6291456);

            final InetSocketAddress addr = new InetSocketAddress(getInt(prop, server, "port"));
            ChannelFuture future = controller.bind(addr).sync();
            if (future.isSuccess())
                LOG.info("Server Ready to serve on " + addr);
            else
                throw new Exception("Address already in use");
        } catch (Throwable t) {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            throw new RuntimeException("Initialization failed", t);
        }
    }
}

From source file:io.micrometer.graphite.GraphiteMeterRegistryTest.java

License:Apache License

@Test
void metricPrefixes() throws InterruptedException {
    final CountDownLatch receiveLatch = new CountDownLatch(1);

    final GraphiteMeterRegistry registry = new GraphiteMeterRegistry(new GraphiteConfig() {
        @Override/*from www . j a  v a2  s.com*/
        @Nullable
        public String get(String key) {
            return null;
        }

        @Override
        public Duration step() {
            return Duration.ofSeconds(1);
        }

        @Override
        public GraphiteProtocol protocol() {
            return GraphiteProtocol.UDP;
        }

        @Override
        public int port() {
            return PORT;
        }

        @Override
        public String[] tagsAsPrefix() {
            return new String[] { "application" };
        }
    }, mockClock);

    Connection server = UdpServer.create().option(ChannelOption.SO_REUSEADDR, true).host("localhost").port(PORT)
            .handle((in, out) -> {
                in.receive().asString().subscribe(line -> {
                    assertThat(line).startsWith("APPNAME.myTimer");
                    receiveLatch.countDown();
                });
                return Flux.never();
            }).bind().doOnSuccess(v -> {
                registry.timer("my.timer", "application", "APPNAME").record(1, TimeUnit.MILLISECONDS);
                registry.close();
            }).block(Duration.ofSeconds(10));

    assertTrue(receiveLatch.await(10, TimeUnit.SECONDS), "line was received");
    server.dispose();
}

From source file:io.moquette.server.netty.NettyAcceptor.java

License:Open Source License

private void initFactory(String host, int port, final PipelineInitializer pipeliner) {
    ServerBootstrap b = new ServerBootstrap();
    b.group(m_bossGroup, m_workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override/*from  w w w.j  a va2 s  .  c o m*/
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    try {
                        pipeliner.init(pipeline);
                    } catch (Throwable th) {
                        LOG.error("Severe error during pipeline creation", th);
                        throw th;
                    }
                }
            }).option(ChannelOption.SO_BACKLOG, 128).option(ChannelOption.SO_REUSEADDR, true)
            .option(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true);
    try {
        // Bind and start to accept incoming connections.
        ChannelFuture f = b.bind(host, port);
        LOG.info("Server binded host: {}, port: {}", host, port);
        f.sync();
    } catch (InterruptedException ex) {
        LOG.error(null, ex);
    }
}

From source file:io.mycat.netty.NettyServer.java

License:Apache License

private ServerBootstrap configServer() {
    bossGroup = new NioEventLoopGroup(args.bossThreads, new DefaultThreadFactory("NettyBossGroup", true));
    workerGroup = new NioEventLoopGroup(args.workerThreads, new DefaultThreadFactory("NettyWorkerGroup", true));
    userExecutor = createUserThreadExecutor();

    final ProtocolHandler handshakeHandler = newHandshakeHandler(userExecutor);
    final ProtocolHandler protocolHandler = newProtocolHandler(userExecutor);

    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.SO_KEEPALIVE, true)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.TCP_NODELAY, true);

    if (args.socketTimeoutMills > 0) {
        b.childOption(ChannelOption.SO_TIMEOUT, args.socketTimeoutMills);
    }//ww w.  j  a va  2s.com

    if (args.recvBuff > 0) {
        b.childOption(ChannelOption.SO_RCVBUF, args.recvBuff);
    }

    if (args.sendBuff > 0) {
        b.childOption(ChannelOption.SO_SNDBUF, args.sendBuff);
    }

    b.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(createProtocolDecoder(), /* createProtocolEncoder(), */ handshakeHandler,
                    protocolHandler);
        }
    });

    return b;
}

From source file:io.nebo.container.NettyEmbeddedServletContainer.java

License:Apache License

private void groups(ServerBootstrap b) {
    if (StandardSystemProperty.OS_NAME.value().equals("Linux")) {
        bossGroup = new EpollEventLoopGroup(1);
        workerGroup = new EpollEventLoopGroup();
        b.channel(EpollServerSocketChannel.class).group(bossGroup, workerGroup)
                .option(EpollChannelOption.TCP_CORK, true);
    } else {//w  w  w  . jav a2s. com
        bossGroup = new NioEventLoopGroup(1);
        workerGroup = new NioEventLoopGroup();
        b.channel(NioServerSocketChannel.class).group(bossGroup, workerGroup);
    }
    b.option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_REUSEADDR, true)
            .option(ChannelOption.SO_BACKLOG, 100);
    logger.info("Bootstrap configuration: " + b.toString());
}

From source file:io.reactivesocket.netty.tcp.client.ClientTcpDuplexConnection.java

License:Apache License

public static Publisher<ClientTcpDuplexConnection> create(SocketAddress address,
        EventLoopGroup eventLoopGroup) {
    return s -> {
        CopyOnWriteArrayList<Observer<Frame>> subjects = new CopyOnWriteArrayList<>();
        ReactiveSocketClientHandler clientHandler = new ReactiveSocketClientHandler(subjects);
        Bootstrap bootstrap = new Bootstrap();
        ChannelFuture connect = bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_REUSEADDR, true)
                .option(ChannelOption.AUTO_READ, true).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override//ww w . ja  va 2  s  .  c  o m
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE >> 1, 0,
                                BitUtil.SIZE_OF_INT, -1 * BitUtil.SIZE_OF_INT, 0), clientHandler);
                    }
                }).connect(address);

        connect.addListener(connectFuture -> {
            if (connectFuture.isSuccess()) {
                Channel ch = connect.channel();
                s.onNext(new ClientTcpDuplexConnection(ch, subjects));
                s.onComplete();
            } else {
                s.onError(connectFuture.cause());
            }
        });
    };
}

From source file:io.vertx.core.http.impl.HttpClientImpl.java

License:Open Source License

private void applyConnectionOptions(Bootstrap bootstrap) {
    bootstrap.option(ChannelOption.TCP_NODELAY, options.isTcpNoDelay());
    if (options.getSendBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, options.getSendBufferSize());
    }//ww  w .  j a  v  a2 s  .  c  o  m
    if (options.getReceiveBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, options.getReceiveBufferSize());
        bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR,
                new FixedRecvByteBufAllocator(options.getReceiveBufferSize()));
    }
    bootstrap.option(ChannelOption.SO_LINGER, options.getSoLinger());
    if (options.getTrafficClass() != -1) {
        bootstrap.option(ChannelOption.IP_TOS, options.getTrafficClass());
    }
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, options.getConnectTimeout());
    bootstrap.option(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, options.isTcpKeepAlive());
    bootstrap.option(ChannelOption.SO_REUSEADDR, options.isReuseAddress());
}

From source file:io.vertx.core.net.impl.NetServerBase.java

License:Open Source License

/**
 * Apply the connection option to the server.
 *
 * @param bootstrap the Netty server bootstrap
 *//*from w w w.ja  v a2s  .  co m*/
protected void applyConnectionOptions(ServerBootstrap bootstrap) {
    bootstrap.childOption(ChannelOption.TCP_NODELAY, options.isTcpNoDelay());
    if (options.getSendBufferSize() != -1) {
        bootstrap.childOption(ChannelOption.SO_SNDBUF, options.getSendBufferSize());
    }
    if (options.getReceiveBufferSize() != -1) {
        bootstrap.childOption(ChannelOption.SO_RCVBUF, options.getReceiveBufferSize());
        bootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR,
                new FixedRecvByteBufAllocator(options.getReceiveBufferSize()));
    }
    if (options.getSoLinger() != -1) {
        bootstrap.option(ChannelOption.SO_LINGER, options.getSoLinger());
    }
    if (options.getTrafficClass() != -1) {
        bootstrap.childOption(ChannelOption.IP_TOS, options.getTrafficClass());
    }
    bootstrap.childOption(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);

    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, options.isTcpKeepAlive());
    bootstrap.option(ChannelOption.SO_REUSEADDR, options.isReuseAddress());
    if (options.getAcceptBacklog() != -1) {
        bootstrap.option(ChannelOption.SO_BACKLOG, options.getAcceptBacklog());
    }
}

From source file:io.vertx.core.net.impl.transport.Transport.java

License:Open Source License

public void configure(DatagramChannel channel, DatagramSocketOptions options) {
    channel.config().setAllocator(PartialPooledByteBufAllocator.INSTANCE);
    if (options.getSendBufferSize() != -1) {
        channel.config().setSendBufferSize(options.getSendBufferSize());
    }/*from www.j a  v  a 2s.co m*/
    if (options.getReceiveBufferSize() != -1) {
        channel.config().setReceiveBufferSize(options.getReceiveBufferSize());
        channel.config().setRecvByteBufAllocator(new FixedRecvByteBufAllocator(options.getReceiveBufferSize()));
    }
    channel.config().setOption(ChannelOption.SO_REUSEADDR, options.isReuseAddress());
    if (options.getTrafficClass() != -1) {
        channel.config().setTrafficClass(options.getTrafficClass());
    }
    channel.config().setBroadcast(options.isBroadcast());
    if (this == Transport.JDK) {
        channel.config().setLoopbackModeDisabled(options.isLoopbackModeDisabled());
        if (options.getMulticastTimeToLive() != -1) {
            channel.config().setTimeToLive(options.getMulticastTimeToLive());
        }
        if (options.getMulticastNetworkInterface() != null) {
            try {
                channel.config().setNetworkInterface(
                        NetworkInterface.getByName(options.getMulticastNetworkInterface()));
            } catch (SocketException e) {
                throw new IllegalArgumentException(
                        "Could not find network interface with name " + options.getMulticastNetworkInterface());
            }
        }
    }
}