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:bftsmart.communication.client.netty.NettyClientServerCommunicationSystemServerSide.java

License:Apache License

public NettyClientServerCommunicationSystemServerSide(ServerViewController controller) {
    try {/* www  .ja va 2 s  .  c o  m*/

        this.controller = controller;
        /* Tulio Ribeiro */
        privKey = controller.getStaticConf().getPrivateKey();

        sessionReplicaToClient = new ConcurrentHashMap<>();
        rl = new ReentrantReadWriteLock();

        // Configure the server.

        serverPipelineFactory = new NettyServerPipelineFactory(this, sessionReplicaToClient, controller, rl);

        EventLoopGroup bossGroup = new NioEventLoopGroup(bossThreads);
        EventLoopGroup workerGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors());

        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_SNDBUF, tcpSendBufferSize)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeoutMsec)
                .option(ChannelOption.SO_BACKLOG, connectionBacklog)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(serverPipelineFactory.getDecoder());
                        ch.pipeline().addLast(serverPipelineFactory.getEncoder());
                        ch.pipeline().addLast(serverPipelineFactory.getHandler());
                    }
                }).childOption(ChannelOption.SO_KEEPALIVE, true).childOption(ChannelOption.TCP_NODELAY, true);
        String myAddress;
        String confAddress = controller.getStaticConf()
                .getRemoteAddress(controller.getStaticConf().getProcessId()).getAddress().getHostAddress();

        if (InetAddress.getLoopbackAddress().getHostAddress().equals(confAddress)) {

            myAddress = InetAddress.getLoopbackAddress().getHostAddress();

        }

        else if (controller.getStaticConf().getBindAddress().equals("")) {

            myAddress = InetAddress.getLocalHost().getHostAddress();

            // If Netty binds to the loopback address, clients will not be able to connect
            // to replicas.
            // To solve that issue, we bind to the address supplied in config/hosts.config
            // instead.
            if (InetAddress.getLoopbackAddress().getHostAddress().equals(myAddress)
                    && !myAddress.equals(confAddress)) {

                myAddress = confAddress;
            }

        } else {

            myAddress = controller.getStaticConf().getBindAddress();
        }

        int myPort = controller.getStaticConf().getPort(controller.getStaticConf().getProcessId());

        ChannelFuture f = b.bind(new InetSocketAddress(myAddress, myPort)).sync();

        logger.info("ID = " + controller.getStaticConf().getProcessId());
        logger.info("N = " + controller.getCurrentViewN());
        logger.info("F = " + controller.getCurrentViewF());
        logger.info("Port (client <-> server) = "
                + controller.getStaticConf().getPort(controller.getStaticConf().getProcessId()));
        logger.info("Port (server <-> server) = "
                + controller.getStaticConf().getServerToServerPort(controller.getStaticConf().getProcessId()));
        logger.info("requestTimeout = " + controller.getStaticConf().getRequestTimeout());
        logger.info("maxBatch = " + controller.getStaticConf().getMaxBatchSize());
        if (controller.getStaticConf().getUseSignatures() == 1)
            logger.info("Using Signatures");
        else if (controller.getStaticConf().getUseSignatures() == 2)
            logger.info("Using benchmark signature verification");
        logger.info("Binded replica to IP address " + myAddress);
        // ******* EDUARDO END **************//

        /* Tulio Ribeiro */
        // SSL/TLS
        logger.info("SSL/TLS enabled, protocol version: {}",
                controller.getStaticConf().getSSLTLSProtocolVersion());

        /* Tulio Ribeiro END */

        mainChannel = f.channel();

    } catch (InterruptedException | UnknownHostException ex) {
        logger.error("Failed to create Netty communication system", ex);
    }
}

From source file:c5db.control.ControlService.java

License:Apache License

private void startHttpRpc() {
    try {//from w  w  w.j a va  2 s . c  o  m
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        ServerBootstrap serverBootstrap1 = serverBootstrap.group(acceptConnectionGroup, ioWorkerGroup)
                .channel(NioServerSocketChannel.class).option(ChannelOption.SO_REUSEADDR, true)
                .option(ChannelOption.SO_BACKLOG, 100).childOption(ChannelOption.TCP_NODELAY, true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();

                        //              pipeline.addLast("logger", new LoggingHandler(LogLevel.DEBUG));
                        pipeline.addLast("http-server", new HttpServerCodec());
                        pipeline.addLast("aggregator",
                                new HttpObjectAggregator(C5ServerConstants.MAX_CALL_SIZE));

                        pipeline.addLast("encode", new ServerHttpProtostuffEncoder());
                        pipeline.addLast("decode", new ServerHttpProtostuffDecoder());

                        pipeline.addLast("translate", new ServerDecodeCommandRequest());

                        pipeline.addLast("inc-messages", new MessageHandler());
                    }
                });

        serverBootstrap.bind(modulePort).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    // yay
                    listenChannel = future.channel();
                    notifyStarted();
                } else {
                    LOG.error("Unable to bind to port {}", modulePort);
                    notifyFailed(future.cause());
                }
            }
        });
    } catch (Exception e) {
        notifyFailed(e);
    }
}

From source file:c5db.control.SimpleControlClient.java

License:Apache License

private void createClient() {
    client.group(ioWorkerGroup).channel(NioSocketChannel.class).option(ChannelOption.SO_REUSEADDR, true)
            .option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {
                @Override/*ww w .  j  a va  2 s .  c om*/
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    //            pipeline.addLast("logger", new LoggingHandler(LogLevel.WARN));
                    pipeline.addLast("http-client", new HttpClientCodec());
                    pipeline.addLast("aggregator", new HttpObjectAggregator(C5ServerConstants.MAX_CALL_SIZE));

                    pipeline.addLast("encode", new ClientHttpProtostuffEncoder());
                    pipeline.addLast("decode", new ClientHttpProtostuffDecoder());

                    pipeline.addLast("translate", new ClientEncodeCommandRequest());
                }
            });
}

From source file:c5db.discovery.BeaconService.java

License:Apache License

@Override
protected void doStart() {
    eventLoopGroup.next().execute(() -> {
        bootstrap = new Bootstrap();
        bootstrap.group(eventLoopGroup).channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true).option(ChannelOption.SO_REUSEADDR, true)
                .handler(new ChannelInitializer<DatagramChannel>() {
                    @Override//from  w  w  w  . jav a 2 s.  com
                    protected void initChannel(DatagramChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();

                        p.addLast("protobufDecoder",
                                new UdpProtostuffDecoder<>(Availability.getSchema(), false));

                        p.addLast("protobufEncoder",
                                new UdpProtostuffEncoder<>(Availability.getSchema(), false));

                        p.addLast("beaconMessageHandler", new BeaconMessageHandler());
                    }
                });
        // Wait, this is why we are in a new executor...
        //noinspection RedundantCast
        bootstrap.bind(discoveryPort).addListener((ChannelFutureListener) future -> {
            if (future.isSuccess()) {
                broadcastChannel = future.channel();
            } else {
                LOG.error("Unable to bind! ", future.cause());
                notifyFailed(future.cause());
            }
        });

        try {
            localIPs = getLocalIPs();
        } catch (SocketException e) {
            LOG.error("SocketException:", e);
            notifyFailed(e);
            return;
        }

        fiber = fiberSupplier.getNewFiber(this::notifyFailed);
        fiber.start();

        // Schedule fiber tasks and subscriptions.
        incomingMessages.subscribe(fiber, this::processWireMessage);
        nodeInfoRequests.subscribe(fiber, this::handleNodeInfoRequest);
        moduleInformationProvider.moduleChangeChannel().subscribe(fiber, this::updateCurrentModulePorts);

        if (localIPs.isEmpty()) {
            LOG.warn(
                    "Found no IP addresses to broadcast to other nodes; as a result, only sending to loopback");
        }

        fiber.scheduleAtFixedRate(this::sendBeacon, BEACON_SERVICE_INITIAL_BROADCAST_DELAY_MILLISECONDS,
                BEACON_SERVICE_BROADCAST_PERIOD_MILLISECONDS, TimeUnit.MILLISECONDS);

        C5Futures.addCallback(moduleInformationProvider.getOnlineModules(),
                (ImmutableMap<ModuleType, Integer> onlineModuleToPortMap) -> {
                    updateCurrentModulePorts(onlineModuleToPortMap);
                    notifyStarted();
                }, this::notifyFailed, fiber);
    });
}

From source file:c5db.eventLogging.EventLogListener.java

License:Apache License

@Override
protected void doStart() {
    nioEventLoopGroup.next().execute(() -> {

        Bootstrap bootstrap = new Bootstrap();
        try {//from   w ww . ja  v a  2  s . c  o  m
            bootstrap.group(nioEventLoopGroup).channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true).option(ChannelOption.SO_REUSEADDR, true)
                    .handler(new ChannelInitializer<DatagramChannel>() {
                        @Override
                        protected void initChannel(DatagramChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast("protostuffDecoder",
                                    new UdpProtostuffDecoder<>(EventLogEntry.getSchema(), false));
                            p.addLast("logger", new MsgHandler());
                        }
                    });

            bootstrap.bind(port).addListener(new GenericFutureListener<ChannelFuture>() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    channel = future.channel();
                }
            });

            notifyStarted();
        } catch (Throwable t) {
            notifyFailed(t);
        }
    });
}

From source file:c5db.eventLogging.EventLogService.java

License:Apache License

@Override
protected void doStart() {
    nioEventLoopGroup.next().execute(() -> {
        Bootstrap bootstrap = new Bootstrap();
        try {/*from ww w .  j  a  va  2 s. c  o m*/
            bootstrap.group(nioEventLoopGroup).channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true).option(ChannelOption.SO_REUSEADDR, true)
                    .handler(new ChannelInitializer<DatagramChannel>() {
                        @Override
                        protected void initChannel(DatagramChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast("protostuffEncoder",
                                    new UdpProtostuffEncoder<>(EventLogEntry.getSchema(), false));
                        }
                    });

            bootstrap.bind(port).addListener(new GenericFutureListener<ChannelFuture>() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    broadcastChannel = future.channel();
                }
            });

            eventLogChannel.subscribe(fiber, msg -> {
                if (broadcastChannel == null) {
                    LOG.debug("Broadcast channel isn't read yet, dropped message");
                    return;
                }

                LOG.trace("Sending event {}", msg);
                broadcastChannel
                        .writeAndFlush(new UdpProtostuffEncoder.UdpProtostuffMessage<>(sendAddress, msg));
            });

            fiber.start();

            notifyStarted();
        } catch (Throwable t) {
            fiber.dispose();

            notifyFailed(t);
        }
    });
}

From source file:c5db.regionserver.RegionServerService.java

License:Apache License

@Override
protected void doStart() {
    fiber.start();/*from ww  w.  j  a v a2s .c om*/

    fiber.execute(() -> {
        // we need the tablet module:
        ListenableFuture<C5Module> f = server.getModule(ModuleType.Tablet);
        Futures.addCallback(f, new FutureCallback<C5Module>() {
            @Override
            public void onSuccess(final C5Module result) {
                tabletModule = (TabletModule) result;
                bootstrap.group(acceptGroup, workerGroup).option(ChannelOption.SO_REUSEADDR, true)
                        .childOption(ChannelOption.TCP_NODELAY, true).channel(NioServerSocketChannel.class)
                        .childHandler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            protected void initChannel(SocketChannel ch) throws Exception {
                                ChannelPipeline p = ch.pipeline();
                                p.addLast("http-server-codec", new HttpServerCodec());
                                p.addLast("http-agg",
                                        new HttpObjectAggregator(C5ServerConstants.MAX_CALL_SIZE));
                                p.addLast("websocket-agg",
                                        new WebSocketFrameAggregator(C5ServerConstants.MAX_CALL_SIZE));
                                p.addLast("decoder", new WebsocketProtostuffDecoder("/websocket"));
                                p.addLast("encoder", new WebsocketProtostuffEncoder());
                                p.addLast("handler", new RegionServerHandler(RegionServerService.this));
                            }
                        });

                bootstrap.bind(port).addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            listenChannel = future.channel();
                            notifyStarted();
                        } else {
                            LOG.error("Unable to find Region Server to {} {}", port, future.cause());
                            notifyFailed(future.cause());
                        }
                    }
                });
            }

            @Override
            public void onFailure(Throwable t) {
                notifyFailed(t);
            }
        }, fiber);
    });
}

From source file:c5db.replication.ReplicatorService.java

License:Apache License

/**
 * ********** Service startup/registration and shutdown/termination **************
 *//*from  w  ww .  ja v a2  s.  c om*/
@Override
protected void doStart() {
    // must start the fiber up early.
    fiber = fiberSupplier.getNewFiber(this::failModule);
    setupEventChannelSubscription();
    fiber.start();

    C5Futures.addCallback(getDependedOnModules(), (ignore) -> {
        ChannelInitializer<SocketChannel> initer = new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                p.addLast("frameDecode", new ProtobufVarint32FrameDecoder());
                p.addLast("pbufDecode", new ProtostuffDecoder<>(ReplicationWireMessage.getSchema()));

                p.addLast("frameEncode", new ProtobufVarint32LengthFieldPrepender());
                p.addLast("pbufEncoder", new ProtostuffEncoder<ReplicationWireMessage>());

                p.addLast(new MessageHandler());
            }
        };

        serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.SO_BACKLOG, 100)
                .childOption(ChannelOption.TCP_NODELAY, true).childHandler(initer);

        //noinspection RedundantCast
        serverBootstrap.bind(port).addListener((ChannelFutureListener) future -> {
            if (future.isSuccess()) {
                LOG.info("successfully bound node {} port {} ", nodeId, port);
                listenChannel = future.channel();
            } else {
                LOG.error("Unable to bind! ", future.cause());
                failModule(future.cause());
            }
        });

        outgoingBootstrap.group(workerGroup).channel(NioSocketChannel.class)
                .option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.TCP_NODELAY, true)
                .handler(initer);

        //noinspection Convert2MethodRef
        outgoingRequests.subscribe(fiber, message -> handleOutgoingMessage(message),
                // Clean up cancelled requests.
                message -> handleCancelledSession(message.getSession()));

        notifyStarted();

    }, (Throwable t) -> {
        LOG.error("ReplicatorService unable to retrieve modules!", t);
        failModule(t);
    }, fiber);
}

From source file:cc.ly.mc.client.netty.SocketClient.java

License:Apache License

public void run() {
    // Configure the server.
    worker = new OioEventLoopGroup();
    Bootstrap b = new Bootstrap();
    b.group(worker).channel(OioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.SO_REUSEADDR, true).handler(new SocketClientInitializer());
    // Start the client.
    channel = b.connect(host, port).channel();
}

From source file:cc.ly.mc.core.client.io.SocketClient.java

License:Apache License

public void run() {
    // Configure the server.
    worker = new OioEventLoopGroup();
    Bootstrap b = new Bootstrap();
    b.group(worker).channel(OioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.SO_REUSEADDR, true)
            .handler(new SocketClientInitializer(connectedListeners, disconnectedListeners));
    // Start the client.
    channel = b.connect(host, port).channel();
}