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:reactor.io.net.impl.netty.tcp.NettyTcpServer.java

License:Apache License

protected NettyTcpServer(Environment env, Dispatcher dispatcher, InetSocketAddress listenAddress,
        final ServerSocketOptions options, final SslOptions sslOptions, Codec<Buffer, IN, OUT> codec) {
    super(env, dispatcher, listenAddress, options, sslOptions, codec);

    if (options instanceof NettyServerSocketOptions) {
        this.nettyOptions = (NettyServerSocketOptions) options;
    } else {/*  w  w w.j ava2 s .  c om*/
        this.nettyOptions = null;
    }

    int selectThreadCount = getDefaultEnvironment().getIntProperty("reactor.tcp.selectThreadCount",
            Environment.PROCESSORS / 2);
    int ioThreadCount = getDefaultEnvironment().getIntProperty("reactor.tcp.ioThreadCount",
            Environment.PROCESSORS);

    this.selectorGroup = new NioEventLoopGroup(selectThreadCount,
            new NamedDaemonThreadFactory("reactor-tcp-select"));

    if (null != nettyOptions && null != nettyOptions.eventLoopGroup()) {
        this.ioGroup = nettyOptions.eventLoopGroup();
    } else {
        this.ioGroup = new NioEventLoopGroup(ioThreadCount, new NamedDaemonThreadFactory("reactor-tcp-io"));
    }

    this.bootstrap = new ServerBootstrap().group(selectorGroup, ioGroup).channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, options.backlog())
            .option(ChannelOption.SO_RCVBUF, options.rcvbuf()).option(ChannelOption.SO_SNDBUF, options.sndbuf())
            .option(ChannelOption.SO_REUSEADDR, options.reuseAddr())
            .localAddress((null == listenAddress ? new InetSocketAddress(0) : listenAddress))
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.AUTO_READ, sslOptions != null);
}

From source file:reactor.io.net.impl.netty.udp.NettyDatagramServer.java

License:Apache License

public NettyDatagramServer(@Nonnull Environment env, @Nonnull Dispatcher dispatcher,
        @Nullable InetSocketAddress listenAddress, @Nullable final NetworkInterface multicastInterface,
        @Nonnull final ServerSocketOptions options, @Nullable Codec<Buffer, IN, OUT> codec) {
    super(env, dispatcher, listenAddress, multicastInterface, options, codec);

    if (options instanceof NettyServerSocketOptions) {
        this.nettyOptions = (NettyServerSocketOptions) options;
    } else {//from w  w  w  .  ja v  a 2  s .c  om
        this.nettyOptions = null;
    }

    if (null != nettyOptions && null != nettyOptions.eventLoopGroup()) {
        this.ioGroup = nettyOptions.eventLoopGroup();
    } else {
        int ioThreadCount = getDefaultEnvironment().getIntProperty("reactor.udp.ioThreadCount",
                Environment.PROCESSORS);
        this.ioGroup = new NioEventLoopGroup(ioThreadCount, new NamedDaemonThreadFactory("reactor-udp-io"));
    }

    final InternetProtocolFamily family = toNettyFamily(options.protocolFamily());

    this.bootstrap = new Bootstrap().group(ioGroup).option(ChannelOption.SO_RCVBUF, options.rcvbuf())
            .option(ChannelOption.SO_SNDBUF, options.sndbuf())
            .option(ChannelOption.SO_REUSEADDR, options.reuseAddr()).option(ChannelOption.AUTO_READ, false)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, options.timeout())
            .channelFactory(new ChannelFactory<Channel>() {
                @Override
                public Channel newChannel() {
                    return new NioDatagramChannel(family);
                }
            });

    if (null != listenAddress) {
        bootstrap.localAddress(listenAddress);
    } else {
        bootstrap.localAddress(NetUtil.LOCALHOST, 3000);
    }
    if (null != multicastInterface) {
        bootstrap.option(ChannelOption.IP_MULTICAST_IF, multicastInterface);
    }
}

From source file:reactor.io.net.netty.tcp.NettyTcpServer.java

License:Apache License

protected NettyTcpServer(@Nonnull Environment env, @Nonnull EventBus reactor,
        @Nullable InetSocketAddress listenAddress, final ServerSocketOptions options,
        final SslOptions sslOptions, @Nullable Codec<Buffer, IN, OUT> codec,
        @Nonnull Collection<Consumer<NetChannel<IN, OUT>>> consumers) {
    super(env, reactor, listenAddress, options, sslOptions, codec, consumers);

    if (options instanceof NettyServerSocketOptions) {
        this.nettyOptions = (NettyServerSocketOptions) options;
    } else {//  ww  w.  ja  v a 2 s  .c  om
        this.nettyOptions = null;
    }

    int selectThreadCount = env.getProperty("reactor.tcp.selectThreadCount", Integer.class,
            Environment.PROCESSORS / 2);
    int ioThreadCount = env.getProperty("reactor.tcp.ioThreadCount", Integer.class, Environment.PROCESSORS);
    this.selectorGroup = new NioEventLoopGroup(selectThreadCount,
            new NamedDaemonThreadFactory("reactor-tcp-select"));
    if (null != nettyOptions && null != nettyOptions.eventLoopGroup()) {
        this.ioGroup = nettyOptions.eventLoopGroup();
    } else {
        this.ioGroup = new NioEventLoopGroup(ioThreadCount, new NamedDaemonThreadFactory("reactor-tcp-io"));
    }

    this.bootstrap = new ServerBootstrap().group(selectorGroup, ioGroup).channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, options.backlog())
            .option(ChannelOption.SO_RCVBUF, options.rcvbuf()).option(ChannelOption.SO_SNDBUF, options.sndbuf())
            .option(ChannelOption.SO_REUSEADDR, options.reuseAddr())
            .localAddress((null == listenAddress ? new InetSocketAddress(3000) : listenAddress))
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(final SocketChannel ch) throws Exception {
                    SocketChannelConfig config = ch.config();
                    config.setReceiveBufferSize(options.rcvbuf());
                    config.setSendBufferSize(options.sndbuf());
                    config.setKeepAlive(options.keepAlive());
                    config.setReuseAddress(options.reuseAddr());
                    config.setSoLinger(options.linger());
                    config.setTcpNoDelay(options.tcpNoDelay());

                    if (log.isDebugEnabled()) {
                        log.debug("CONNECT {}", ch);
                    }

                    if (null != sslOptions) {
                        SSLEngine ssl = new SSLEngineSupplier(sslOptions, false).get();
                        if (log.isDebugEnabled()) {
                            log.debug("SSL enabled using keystore {}",
                                    (null != sslOptions.keystoreFile() ? sslOptions.keystoreFile()
                                            : "<DEFAULT>"));
                        }
                        ch.pipeline().addLast(new SslHandler(ssl));
                    }
                    if (null != nettyOptions && null != nettyOptions.pipelineConfigurer()) {
                        nettyOptions.pipelineConfigurer().accept(ch.pipeline());
                    }
                    ch.pipeline().addLast(createChannelHandlers(ch));
                    ch.closeFuture().addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture future) throws Exception {
                            if (log.isDebugEnabled()) {
                                log.debug("CLOSE {}", ch);
                            }
                            close(ch);
                        }
                    });
                }
            });
}

From source file:reactor.io.net.netty.udp.NettyDatagramServer.java

License:Apache License

public NettyDatagramServer(@Nonnull Environment env, @Nonnull EventBus reactor,
        @Nullable InetSocketAddress listenAddress, @Nullable final NetworkInterface multicastInterface,
        @Nonnull final ServerSocketOptions options, @Nullable Codec<Buffer, IN, OUT> codec,
        Collection<Consumer<NetChannel<IN, OUT>>> consumers) {
    super(env, reactor, listenAddress, multicastInterface, options, codec, consumers);

    if (options instanceof NettyServerSocketOptions) {
        this.nettyOptions = (NettyServerSocketOptions) options;
    } else {/*w  w w. ja  va2 s  .  c o m*/
        this.nettyOptions = null;
    }

    if (null != nettyOptions && null != nettyOptions.eventLoopGroup()) {
        this.ioGroup = nettyOptions.eventLoopGroup();
    } else {
        int ioThreadCount = env.getProperty("reactor.udp.ioThreadCount", Integer.class, Environment.PROCESSORS);
        this.ioGroup = new NioEventLoopGroup(ioThreadCount, new NamedDaemonThreadFactory("reactor-udp-io"));
    }

    final NettyNetChannelInboundHandler inboundHandler = new NettyNetChannelInboundHandler() {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            super.channelRead(ctx, ((DatagramPacket) msg).content());
        }
    };

    this.bootstrap = new Bootstrap().group(ioGroup).option(ChannelOption.SO_RCVBUF, options.rcvbuf())
            .option(ChannelOption.SO_SNDBUF, options.sndbuf())
            .option(ChannelOption.SO_REUSEADDR, options.reuseAddr())
            .channelFactory(new ChannelFactory<Channel>() {
                @Override
                public Channel newChannel() {
                    final NioDatagramChannel ch = new NioDatagramChannel();
                    DatagramChannelConfig config = ch.config();
                    config.setReceiveBufferSize(options.rcvbuf());
                    config.setSendBufferSize(options.sndbuf());
                    config.setReuseAddress(options.reuseAddr());

                    if (null != multicastInterface) {
                        config.setNetworkInterface(multicastInterface);
                    }

                    if (null != nettyOptions && null != nettyOptions.pipelineConfigurer()) {
                        nettyOptions.pipelineConfigurer().accept(ch.pipeline());
                    }

                    ch.closeFuture().addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture future) throws Exception {
                            if (log.isInfoEnabled()) {
                                log.info("CLOSE {}", ch);
                            }
                            close(ch);
                        }
                    });

                    netChannel = (NettyNetChannel<IN, OUT>) select(ch);
                    inboundHandler.setNetChannel(netChannel);

                    ch.pipeline().addLast(new ChannelOutboundHandlerAdapter() {
                        @Override
                        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
                                throws Exception {
                            super.write(ctx, msg, promise);
                        }
                    });

                    return ch;
                }
            }).handler(inboundHandler);

    if (null != listenAddress) {
        bootstrap.localAddress(listenAddress);
    } else {
        bootstrap.localAddress(NetUtil.LOCALHOST, 3000);
    }
    if (null != multicastInterface) {
        bootstrap.option(ChannelOption.IP_MULTICAST_IF, multicastInterface);
    }
}

From source file:reactor.ipc.netty.options.ServerOptions.java

License:Open Source License

static void defaultServerOptions(ServerBootstrap bootstrap) {
    bootstrap.localAddress(LOCALHOST_AUTO_PORT).option(ChannelOption.SO_REUSEADDR, true)
            .option(ChannelOption.SO_BACKLOG, 1000)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.SO_RCVBUF, 1024 * 1024).childOption(ChannelOption.SO_SNDBUF, 1024 * 1024)
            .childOption(ChannelOption.AUTO_READ, false).childOption(ChannelOption.SO_KEEPALIVE, true)
            .childOption(ChannelOption.SO_LINGER, 0).childOption(ChannelOption.TCP_NODELAY, true)
            .childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30000);
}

From source file:reactor.ipc.netty.udp.UdpServerTests.java

License:Open Source License

@Test
@SuppressWarnings("unchecked")
public void supportsUdpMulticast() throws Exception {
    final int port = SocketUtils.findAvailableUdpPort();
    final CountDownLatch latch = new CountDownLatch(Schedulers.DEFAULT_POOL_SIZE);
    Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();

    final InetAddress multicastGroup = InetAddress.getByName("230.0.0.1");
    final NetworkInterface multicastInterface = findMulticastEnabledIPv4Interface();
    log.info("Using network interface '{}' for multicast", multicastInterface);
    final Collection<NettyContext> servers = new ArrayList<>();

    for (int i = 0; i < 4; i++) {
        NettyContext server = UdpClient.create(opts -> opts.option(ChannelOption.SO_REUSEADDR, true)
                .connect(port).protocolFamily(InternetProtocolFamily.IPv4)).newHandler((in, out) -> {
                    Flux.<NetworkInterface>generate(s -> {
                        if (ifaces.hasMoreElements()) {
                            s.next(ifaces.nextElement());
                        } else {
                            s.complete();
                        }/*w  ww .ja  va2  s . c  o m*/
                    }).flatMap(iface -> {
                        if (isMulticastEnabledIPv4Interface(iface)) {
                            return in.join(multicastGroup, iface);
                        }
                        return Flux.empty();
                    }).thenMany(in.receive().asByteArray()).log().subscribe(bytes -> {
                        if (bytes.length == 1024) {
                            latch.countDown();
                        }
                    });
                    return Flux.never();
                }).block();

        servers.add(server);
    }

    for (int i = 0; i < Schedulers.DEFAULT_POOL_SIZE; i++) {
        threadPool.submit(() -> {
            try {
                MulticastSocket multicast = new MulticastSocket();
                multicast.joinGroup(new InetSocketAddress(multicastGroup, port), multicastInterface);

                byte[] data = new byte[1024];
                new Random().nextBytes(data);

                multicast.send(new DatagramPacket(data, data.length, multicastGroup, port));

                multicast.close();
            } catch (Exception e) {
                throw new IllegalStateException(e);
            }
        }).get(5, TimeUnit.SECONDS);
    }

    latch.await(5, TimeUnit.SECONDS);
    assertThat("latch was not counted down enough: " + latch.getCount() + " left on " + (4 ^ 2),
            latch.getCount() == 0);

    for (NettyContext s : servers) {
        s.dispose();
    }
}

From source file:sailfish.remoting.DefaultServer.java

License:Apache License

private ServerBootstrap newServerBootstrap() {
    ServerBootstrap serverBoot = new ServerBootstrap();
    serverBoot.channel(NettyPlatformIndependent.serverChannelClass());
    // connections wait for accept
    serverBoot.option(ChannelOption.SO_BACKLOG, 1024);
    serverBoot.option(ChannelOption.SO_REUSEADDR, true);
    // replace by heart beat
    serverBoot.childOption(ChannelOption.SO_KEEPALIVE, false);
    serverBoot.childOption(ChannelOption.TCP_NODELAY, true);
    serverBoot.childOption(ChannelOption.SO_SNDBUF, 32 * 1024);
    serverBoot.childOption(ChannelOption.SO_RCVBUF, 32 * 1024);
    // temporary settings, need more tests
    serverBoot.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK,
            new WriteBufferWaterMark(8 * 1024, 32 * 1024));
    serverBoot.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    //default is true, reduce thread context switching
    serverBoot.childOption(ChannelOption.SINGLE_EVENTEXECUTOR_PER_GROUP, true);
    return serverBoot;
}

From source file:se.sics.gvod.net.NettyNetwork.java

License:Open Source License

/**
 * Start listening as a server at the given address..
 *
 * @param addr the address to listen at//from  www.  j ava  2s. c o  m
 * @param port the port number to listen at
 * @param bindAllNetworkIfs whether to bind on all network interfaces
 * @return true if listening was started
 * @throws ChannelException in case binding failed
 */
private boolean bindUdpPort(final InetAddress addr, final int port, final boolean bindAllNetworkIfs) {

    if (udpPortsToSockets.containsKey(port)) {
        return true;
    }

    EventLoopGroup group = new NioEventLoopGroup();
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(group).channel(NioDatagramChannel.class)
            .handler(new NettyMsgHandler(component, Transport.UDP, msgDecoderClass));

    // Allow packets as large as up to 1600 bytes (default is 768).
    // You could increase or decrease this value to avoid truncated packets
    // or to improve memory footprint respectively.
    //
    // Please also note that a large UDP packet might be truncated or
    // dropped by your router no matter how you configured this option.
    // In UDP, a packet is truncated or dropped if it is larger than a
    // certain size, depending on router configuration. IPv4 routers
    // truncate and IPv6 routers drop a large packet. That's why it is
    // safe to send small packets in UDP.
    bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(1500));
    bootstrap.option(ChannelOption.SO_RCVBUF, RECV_BUFFER_SIZE);

    bootstrap.option(ChannelOption.SO_SNDBUF, SEND_BUFFER_SIZE);
    // bootstrap.setOption("trafficClass", trafficClass);
    // bootstrap.setOption("soTimeout", soTimeout);
    // bootstrap.setOption("broadcast", broadcast);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT_MS);
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);

    try {
        DatagramChannel c;
        if (bindAllNetworkIfs) {
            c = (DatagramChannel) bootstrap.bind(
                    //                        new InetSocketAddress(port)
                    port).sync().channel();
        } else {
            c = (DatagramChannel) bootstrap.bind(new InetSocketAddress(addr, port)).sync().channel();
        }

        addLocalSocket(new InetSocketAddress(addr, port), c);
        logger.debug("Successfully bound to ip:port {}:{}", addr, port);
    } catch (InterruptedException e) {
        logger.warn("Problem when trying to bind to {}:{}", addr.getHostAddress(), port);
        trigger(new Fault(e.getCause()), control);
        return false;
    }

    udpSocketsToBootstraps.put(new InetSocketAddress(addr, port), bootstrap);

    return true;
}

From source file:se.sics.gvod.net.NettyNetwork.java

License:Open Source License

/**
 * Start listening as a server at the given address..
 *
 * @param addr the address to listen at/*from w w w  . j ava2 s .  co m*/
 * @param port the port number to listen at
 * @param bindAllNetworkIfs whether to bind on all network interfaces
 * @return true if listening was started
 * @throws ChannelException in case binding failed
 */
private boolean bindTcpPort(InetAddress addr, int port, boolean bindAllNetworkIfs) {

    if (tcpPortsToSockets.containsKey(port)) {
        return true;
    }

    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    NettyTcpServerHandler handler = new NettyTcpServerHandler(component);
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler((new NettyInitializer<SocketChannel>(handler, msgDecoderClass)))
            .option(ChannelOption.SO_REUSEADDR, true);

    try {
        if (bindAllNetworkIfs) {
            bootstrap.bind(new InetSocketAddress(port)).sync();
        } else {
            bootstrap.bind(new InetSocketAddress(addr, port)).sync();
        }

        logger.debug("Successfully bound to ip:port {}:{}", addr, port);
    } catch (InterruptedException e) {
        logger.warn("Problem when trying to bind to {}:{}", addr.getHostAddress(), port);
        trigger(new Fault(e.getCause()), control);
        return false;
    }

    InetSocketAddress iAddr = new InetSocketAddress(addr, port);
    tcpPortsToSockets.put(port, iAddr);
    tcpSocketsToServerBootstraps.put(iAddr, bootstrap);

    return true;
}

From source file:se.sics.gvod.net.NettyNetwork.java

License:Open Source License

/**
 * Start listening as a server at the given address..
 *
 * @param addr the address to listen at// ww w.ja  v  a2s . c o m
 * @param port the port number to listen at
 * @param bindAllNetworkIfs whether to bind on all network interfaces
 * @return true if listening was started
 * @throws ChannelException in case binding failed
 */
private boolean bindUdtPort(InetAddress addr, int port, boolean bindAllNetworkIfs) {

    if (udtPortsToSockets.containsKey(port)) {
        return true;
    }

    ThreadFactory bossFactory = new UtilThreadFactory("boss");
    ThreadFactory workerFactory = new UtilThreadFactory("worker");
    NioEventLoopGroup bossGroup = new NioEventLoopGroup(1, bossFactory, NioUdtProvider.BYTE_PROVIDER);
    NioEventLoopGroup workerGroup = new NioEventLoopGroup(1, workerFactory, NioUdtProvider.BYTE_PROVIDER);
    NettyUdtServerHandler handler = new NettyUdtServerHandler(component);
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup).channelFactory(NioUdtProvider.BYTE_ACCEPTOR)
            .childHandler(new NettyInitializer<UdtChannel>(handler, msgDecoderClass))
            .option(ChannelOption.SO_REUSEADDR, true);

    try {
        if (bindAllNetworkIfs) {
            bootstrap.bind(new InetSocketAddress(port)).sync();
        } else {
            bootstrap.bind(new InetSocketAddress(addr, port)).sync();
        }

        logger.debug("Successfully bound to ip:port {}:{}", addr, port);
    } catch (InterruptedException e) {
        logger.warn("Problem when trying to bind to {}:{}", addr.getHostAddress(), port);
        trigger(new Fault(e.getCause()), control);
        return false;
    }

    InetSocketAddress iAddr = new InetSocketAddress(addr, port);
    udtPortsToSockets.put(port, iAddr);
    udtSocketsToServerBootstraps.put(iAddr, bootstrap);

    return true;
}