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:com.mpush.netty.client.NettyClient.java

License:Apache License

@Override
public void start(final Listener listener) {
    if (started.compareAndSet(false, true)) {
        Bootstrap bootstrap = new Bootstrap();
        workerGroup = new NioEventLoopGroup();
        bootstrap.group(workerGroup)//
                .option(ChannelOption.TCP_NODELAY, true)//
                .option(ChannelOption.SO_REUSEADDR, true)//
                .option(ChannelOption.SO_KEEPALIVE, true)//
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)//
                .channel(NioSocketChannel.class).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 4000);

        bootstrap.handler(new ChannelInitializer<SocketChannel>() { // (4)
            @Override//from   w  ww. jav a 2  s  .  com
            public void initChannel(SocketChannel ch) throws Exception {
                initPipeline(ch.pipeline());
            }
        });

        ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    if (listener != null)
                        listener.onSuccess(port);
                    LOGGER.info("start netty client success, host={}, port={}", host, port);
                } else {
                    if (listener != null)
                        listener.onFailure(future.cause());
                    LOGGER.error("start netty client failure, host={}, port={}", host, port, future.cause());
                }
            }
        });
    } else {
        listener.onFailure(new ServiceException("client has started!"));
    }
}

From source file:com.mpush.netty.client.NettyTCPClient.java

License:Apache License

private void createClient(Listener listener, EventLoopGroup workerGroup,
        ChannelFactory<? extends Channel> channelFactory) {
    this.workerGroup = workerGroup;
    this.bootstrap = new Bootstrap();
    bootstrap.group(workerGroup)//
            .option(ChannelOption.SO_REUSEADDR, true)//
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)//
            .channelFactory(channelFactory);
    bootstrap.handler(new ChannelInitializer<Channel>() { // (4)
        @Override/*from  w w  w.  j a  va 2  s  .  c  om*/
        public void initChannel(Channel ch) throws Exception {
            initPipeline(ch.pipeline());
        }
    });
    initOptions(bootstrap);
    listener.onSuccess();
}

From source file:com.mpush.netty.http.NettyHttpClient.java

License:Apache License

@Override
protected void doStart(Listener listener) throws Throwable {
    workerGroup = new NioEventLoopGroup(http_work, new DefaultThreadFactory(ThreadNames.T_HTTP_CLIENT));
    b = new Bootstrap();
    b.group(workerGroup);//  ww w. j  a  v a  2 s.co  m
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.option(ChannelOption.TCP_NODELAY, true);
    b.option(ChannelOption.SO_REUSEADDR, true);
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 4000);
    b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("decoder", new HttpResponseDecoder());
            ch.pipeline().addLast("aggregator", new HttpObjectAggregator(maxContentLength));
            ch.pipeline().addLast("encoder", new HttpRequestEncoder());
            ch.pipeline().addLast("handler", new HttpClientHandler(NettyHttpClient.this));
        }
    });
    timer = new HashedWheelTimer(new NamedThreadFactory(T_HTTP_TIMER), 1, TimeUnit.SECONDS, 64);
    listener.onSuccess();
}

From source file:com.mpush.netty.udp.NettyUDPConnector.java

License:Apache License

protected void initOptions(Bootstrap b) {
    b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    b.option(ChannelOption.SO_REUSEADDR, true);
}

From source file:com.mpush.test.client.ConnClientBoot.java

License:Apache License

@Override
protected void doStart(Listener listener) throws Throwable {
    ServiceDiscoveryFactory.create().syncStart();
    CacheManagerFactory.create().init();

    this.workerGroup = new NioEventLoopGroup();
    this.bootstrap = new Bootstrap();
    bootstrap.group(workerGroup)//
            .option(ChannelOption.TCP_NODELAY, true)//
            .option(ChannelOption.SO_REUSEADDR, true)//
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)//
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 60 * 1000)
            .option(ChannelOption.SO_RCVBUF, 5 * 1024 * 1024).channel(NioSocketChannel.class);

    bootstrap.handler(new ChannelInitializer<SocketChannel>() { // (4)
        @Override//from w  w w.  java2  s.  c  o  m
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("decoder", new PacketDecoder());
            ch.pipeline().addLast("encoder", PacketEncoder.INSTANCE);
            ch.pipeline().addLast("handler", new ConnClientChannelHandler());
        }
    });

    listener.onSuccess();
}

From source file:com.navercorp.nbasearc.gcp.PhysicalConnection.java

License:Apache License

static PhysicalConnection create(String ip, int port, SingleThreadEventLoop eventLoop, Gateway gw,
        int reconnectInterval) {
    final PhysicalConnection pc = new PhysicalConnection(ip, port, eventLoop, gw, reconnectInterval);

    pc.b.group(eventLoop.getEventLoopGroup()).channel(NioSocketChannel.class)
            .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_REUSEADDR, true)
            .option(ChannelOption.SO_KEEPALIVE, true).option(ChannelOption.SO_LINGER, 0)
            .option(ChannelOption.SO_SNDBUF, SOCKET_BUFFER).option(ChannelOption.SO_RCVBUF, SOCKET_BUFFER)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override//  w w w .ja va2  s  .c  o m
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(pc.new PhysicalConnectionHandler());
                }
            });

    return pc;
}

From source file:com.navercorp.pinpoint.grpc.server.ServerFactory.java

License:Apache License

private void setupServerOption(final NettyServerBuilder builder) {
    // TODO @see PinpointServerAcceptor
    builder.withChildOption(ChannelOption.TCP_NODELAY, true);
    builder.withChildOption(ChannelOption.SO_REUSEADDR, true);
    builder.withChildOption(ChannelOption.SO_RCVBUF, this.serverOption.getReceiveBufferSize());
    builder.withChildOption(ChannelOption.SO_BACKLOG, this.serverOption.getBacklogQueueSize());
    builder.withChildOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, this.serverOption.getConnectTimeout());
    final WriteBufferWaterMark writeBufferWaterMark = new WriteBufferWaterMark(
            this.serverOption.getWriteBufferLowWaterMark(), this.serverOption.getWriteBufferHighWaterMark());
    builder.withChildOption(ChannelOption.WRITE_BUFFER_WATER_MARK, writeBufferWaterMark);

    builder.handshakeTimeout(this.serverOption.getHandshakeTimeout(), TimeUnit.MILLISECONDS);
    builder.flowControlWindow(this.serverOption.getFlowControlWindow());

    builder.maxInboundMessageSize(this.serverOption.getMaxInboundMessageSize());
    builder.maxHeaderListSize(this.serverOption.getMaxHeaderListSize());

    builder.keepAliveTime(this.serverOption.getKeepAliveTime(), TimeUnit.MILLISECONDS);
    builder.keepAliveTimeout(this.serverOption.getKeepAliveTimeout(), TimeUnit.MILLISECONDS);
    builder.permitKeepAliveTime(this.serverOption.getPermitKeepAliveTimeout(), TimeUnit.MILLISECONDS);
    builder.permitKeepAliveWithoutCalls(this.serverOption.isPermitKeepAliveWithoutCalls());

    builder.maxConnectionIdle(this.serverOption.getMaxConnectionIdle(), TimeUnit.MILLISECONDS);
    builder.maxConnectionAge(this.serverOption.getMaxConnectionAge(), TimeUnit.MILLISECONDS);
    builder.maxConnectionAgeGrace(this.serverOption.getMaxConnectionAgeGrace(), TimeUnit.MILLISECONDS);
    builder.maxConcurrentCallsPerConnection(this.serverOption.getMaxConcurrentCallsPerConnection());
    if (logger.isInfoEnabled()) {
        logger.info("Set serverOption {}. name={}, hostname={}, port={}", serverOption, name, hostname, port);
    }/*  ww w.  j a v  a  2  s.  c o m*/
}

From source file:com.newlandframework.avatarmq.broker.server.AvatarMQBrokerServer.java

License:Apache License

public void init() {
    try {//w  ww  . j  a  v  a  2s  . c o m
        handler = new MessageBrokerHandler().buildConsumerHook(new ConsumerMessageHook())
                .buildProducerHook(new ProducerMessageHook());

        boss = new NioEventLoopGroup(1, threadBossFactory);

        workers = new NioEventLoopGroup(parallel, threadWorkerFactory, NettyUtil.getNioSelectorProvider());

        KryoCodecUtil util = new KryoCodecUtil(KryoPoolFactory.getKryoPoolInstance());

        bootstrap = new ServerBootstrap();

        bootstrap.group(boss, workers).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024).option(ChannelOption.SO_REUSEADDR, true)
                .option(ChannelOption.SO_KEEPALIVE, false).childOption(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_SNDBUF, nettyClustersConfig.getClientSocketSndBufSize())
                .option(ChannelOption.SO_RCVBUF, nettyClustersConfig.getClientSocketRcvBufSize())
                .handler(new LoggingHandler(LogLevel.INFO)).localAddress(serverIpAddr)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(defaultEventExecutorGroup, new MessageObjectEncoder(util),
                                new MessageObjectDecoder(util), handler);
                    }
                });

        super.init();
    } catch (IOException ex) {
        Logger.getLogger(AvatarMQBrokerServer.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.openddal.server.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();
    Authenticator authenticator = createAuthenticator();
    ProcessorFactory processorFactory = createProcessorFactory();
    RequestFactory requestFactory = createRequestFactory();
    ResponseFactory responseFactory = createResponseFactory();
    final ProtocolHandler protocolHandler = new ProtocolHandler(authenticator, processorFactory, requestFactory,
            responseFactory, 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);
    }/*from   www  .ja va 2  s.  c o m*/

    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(), */ protocolHandler);
        }
    });

    return b;
}

From source file:com.seagate.kinetic.client.io.provider.nio.udt.UdtTransportProvider.java

License:Open Source License

private void initTransport() throws KineticException {

    this.port = this.config.getPort();

    this.host = this.config.getHost();

    try {/*  w  ww  .j  av  a  2  s  .co  m*/

        workerGroup = UdtWorkerGroup.getWorkerGroup();

        udtChannelInitializer = new UdtClientChannelInitializer(this.mservice);

        bootstrap = new Bootstrap();

        bootstrap.group(workerGroup).channelFactory(NioUdtProvider.MESSAGE_CONNECTOR)
                .option(ChannelOption.SO_REUSEADDR, true).handler(udtChannelInitializer);

        channel = bootstrap.connect(host, port).sync().channel();

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

    logger.info("udt client connected to host:port =" + host + ":" + port);
}