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.ratpackframework.bootstrap.internal.NettyRatpackService.java

License:Apache License

@Override
protected void startUp() throws Exception {
    ServerBootstrap bootstrap = new ServerBootstrap();
    group = new NioEventLoopGroup(MultithreadEventLoopGroup.DEFAULT_EVENT_LOOP_THREADS,
            new DefaultThreadFactory("ratpack-group", Thread.MAX_PRIORITY));

    bootstrap.group(group).channel(NioServerSocketChannel.class).childHandler(channelInitializer);

    bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    bootstrap.childOption(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    bootstrap.option(ChannelOption.SO_BACKLOG, 1024);

    channel = bootstrap.bind(requestedAddress).sync().channel();
    boundAddress = (InetSocketAddress) channel.localAddress();

    if (logger.isLoggable(Level.INFO)) {
        logger.info(String.format("Ratpack started for http://%s:%s", getBindHost(), getBindPort()));
    }//from  w  w  w .ja  v a2s .  c  o m
}

From source file:org.ratpackframework.server.internal.NettyRatpackService.java

License:Apache License

@Override
protected void startUp() throws Exception {
    ServerBootstrap bootstrap = new ServerBootstrap();
    group = new NioEventLoopGroup(launchConfig.getMainThreads(),
            new DefaultThreadFactory("ratpack-group", Thread.MAX_PRIORITY));

    bootstrap.group(group).channel(NioServerSocketChannel.class).childHandler(channelInitializer)
            .childOption(ChannelOption.ALLOCATOR, launchConfig.getBufferAllocator())
            .childOption(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_REUSEADDR, true)
            .option(ChannelOption.SO_BACKLOG, 1024)
            .option(ChannelOption.ALLOCATOR, launchConfig.getBufferAllocator());

    try {//w  w  w  .ja v  a  2s .  c o  m
        channel = bootstrap.bind(buildSocketAddress()).sync().channel();
    } catch (Exception e) {
        partialShutdown();
        throw e;
    }
    boundAddress = (InetSocketAddress) channel.localAddress();

    if (logger.isLoggable(Level.INFO)) {
        logger.info(String.format("Ratpack started for http://%s:%s", getBindHost(), getBindPort()));
    }
}

From source file:org.rzo.netty.ahessian.application.jmx.remote.client.Client.java

License:Apache License

public static void main(String[] args) throws Exception {

    // InternalLoggerFactory.setDefaultFactory(new SimpleLoggerFactory());
    final ExecutorService executor = Executors.newCachedThreadPool();

    Bootstrap bootstrap = new Bootstrap();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    // workerGroup.setIoRatio(99);
    bootstrap.group(workerGroup);// ww  w .  j a v a 2  s . c o  m
    bootstrap.channel(NioSocketChannel.class);

    bootstrap.remoteAddress(new InetSocketAddress("localhost", 15009));
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);

    final HessianProxyFactory factory = new HessianProxyFactory(executor, "localhost:15009");
    bootstrap.handler(new RPCClientSessionPipelineFactory(
            new RPCClientMixinPipelineFactory(executor, factory, workerGroup), bootstrap));

    factory.setDisconnectedListener(new Runnable() {
        public void run() {
            // stop = true;
        }
    });

    factory.setNewSessionListener(new Runnable() {
        public void run() {
            stop = false;
            executor.execute(new Runnable() {
                public void run() {
                    System.out.println("started work thread");
                    Map options = new HashMap();
                    options.put("sync", true);
                    options.put("timeout", (long) 10000);
                    AsyncMBeanServerConnection service = (AsyncMBeanServerConnection) factory
                            .create(AsyncMBeanServerConnection.class, Client.class.getClassLoader(), options);
                    server = new MBeanServerConnectionAsyncAdapter(service);

                    while (!stop) {
                        try {
                            ObjectName on = new ObjectName("java.lang:type=ClassLoading");
                            Object x = server.getAttribute(on, "LoadedClassCount");
                            System.out.println(x);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                            System.out.println(ex);
                        }
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("stopped work thread");
                }
            });
        }
    });

    // Start the connection attempt.
    ChannelFuture future = bootstrap.connect(new InetSocketAddress("localhost", 15009));
    // Wait until the connection attempt succeeds or fails.
    Channel channel = future.awaitUninterruptibly().channel();
    if (future.isSuccess())
        System.out.println("connected");

    // get a proxy

}

From source file:org.rzo.netty.ahessian.bootstrap.DefaultServer.java

License:Apache License

private void setChannelOptions(Set<String> channelOptions) {
    if (channelOptions == null)
        return;//w w w  . java2s  . co m
    // TODO add more options
    if (channelOptions.contains("IPTOS_THROUGHPUT"))
        bootstrap.childOption(ChannelOption.IP_TOS, IPTOS_THROUGHPUT);
    else if (channelOptions.contains("IPTOS_LOWDELAY"))
        bootstrap.childOption(ChannelOption.IP_TOS, IPTOS_LOWDELAY);
    else if (channelOptions.contains("TCP_NODELAY"))
        bootstrap.childOption(ChannelOption.TCP_NODELAY, true);
    else if (channelOptions.contains("SO_REUSE"))
        bootstrap.childOption(ChannelOption.SO_REUSEADDR, true);

}

From source file:org.rzo.yajsw.app.WrapperManagerImpl.java

License:Apache License

public void start() {
    try {//ww  w. j  a  v a 2  s .  c  o  m
        // hack: avoid netty hangs on connect
        if (_config.getBoolean("wrapper.console.pipestreams", false)) {
            Socket dummy = new Socket("127.0.0.1", _port);
            OutputStream out = dummy.getOutputStream();
            out.close();
            dummy.close();
        }
    } catch (Throwable e1) {
        if (_debug > 1)
            e1.printStackTrace();
    }

    connector = new Bootstrap();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    // workerGroup.setIoRatio(99);
    connector.group(workerGroup);
    connector.channel(NioSocketChannel.class);

    connector.remoteAddress(new InetSocketAddress("127.0.0.1", _port));
    connector.option(ChannelOption.SO_REUSEADDR, true);
    connector.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10 * 1000);
    connector.option(ChannelOption.TCP_NODELAY, true);

    if (_debugComm)
        connector.handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline()
                        .addLast(new io.netty.channel.ChannelHandler[] {
                                new SystemOutLoggingFilter("WrapperManager"),
                                new DelimiterBasedFrameDecoder(8192, true, Delimiters.nulDelimiter()),
                                new MessageEncoder(), new MessageDecoder(), new WrapperHandler() }

                );
            }

        });
    else
        connector.handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline()
                        .addLast(new io.netty.channel.ChannelHandler[] {
                                new DelimiterBasedFrameDecoder(8192, true, Delimiters.nulDelimiter()),
                                new MessageEncoder(), new MessageDecoder(), new WrapperHandler() }

                );
            }

        });

    // pinger is a cycler with high priority threads
    // sends ping messages within a ping interval
    _pinger = new Cycler(getPingInterval(), 0,
            Executors.newCachedThreadPool(new DaemonThreadFactory("pinger", Thread.MAX_PRIORITY)),
            new Runnable() {
                long start = System.currentTimeMillis();

                public void run() {
                    ChannelFuture future;
                    if (_session != null && _session.isActive() && !_stopping && !_appearHanging) {
                        synchronized (_heapDataLock) {
                            if (_sendHeapData) {
                                if (minorGCDuration == -1)
                                    getGCData();
                                future = _session.writeAndFlush(
                                        new Message(Constants.WRAPPER_MSG_PING, "" + currentPercentHeap + ";"
                                                + minorGCDuration + ";" + fullGCDuration + ";" + lastUsedHeap));
                                currentPercentHeap = -1;
                                minorGCDuration = -1;
                                fullGCDuration = -1;
                            } else {
                                future = _session.writeAndFlush(new Message(Constants.WRAPPER_MSG_PING, ""));
                            }
                        }
                        try {
                            future.await(10000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        start = System.currentTimeMillis();
                    } else if ((_haltAppOnWrapper && (System.currentTimeMillis() - start) > _startupTimeout)
                            && !_stopping) {
                        System.out.println("no connection to wrapper during " + (_startupTimeout / 1000)
                                + " seconds -> System.exit(-1)");
                        System.out.println(
                                "if this is due to server overload consider increasing yajsw configuration property wrapper.startup.timeout");
                        System.exit(-1);
                    }
                }
            });
    _pinger.start();

    // connect
    // handler should process messages in a separate thread

    reconnect();
    /*
     * try { if (_config.getInt("wrapper.action.port") > 0) { _actionHandler
     * = new ActionHandler(this, _config); _actionHandler.start(); } } catch
     * (Exception ex) { log.info("could not start action handler " +
     * ex.getMessage()); }
     */

}

From source file:org.springframework.boot.context.embedded.netty.NettyEmbeddedServletContainer.java

License:Apache License

private void groups(ServerBootstrap b) {
    //comment the epoll codes, the epoll evn is hard to build
    /*  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  .  j  a  va2s.  co m*/
    bossGroup = new NioEventLoopGroup(1);
    workerGroup = new NioEventLoopGroup();
    b.channel(NioServerSocketChannel.class)
            .group(bossGroup, workerGroup);
      }*/
    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:org.vertx.java.core.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  ww.  j  a v  a2s.  c  om
    if (tcpReceiveBufferSize != -1) {
        bootstrap.childOption(ChannelOption.SO_RCVBUF, tcpReceiveBufferSize);
        bootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR,
                new FixedRecvByteBufAllocator(tcpReceiveBufferSize));
    }

    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:org.waarp.common.utility.WaarpNettyUtil.java

License:Open Source License

/**
 * Add default configuration for client bootstrap
 * /*ww w .j  a  va2 s . c o  m*/
 * @param bootstrap
 * @param group
 * @param timeout
 */
public static void setBootstrap(Bootstrap bootstrap, EventLoopGroup group, int timeout) {
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.group(group);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeout);
    bootstrap.option(ChannelOption.SO_RCVBUF, 1048576);
    bootstrap.option(ChannelOption.SO_SNDBUF, 1048576);
}

From source file:org.waarp.common.utility.WaarpNettyUtil.java

License:Open Source License

/**
 * Add default configuration for server bootstrap
 * //from  w  w w . j a  v  a  2  s.  co  m
 * @param bootstrap
 * @param groupBoss
 * @param groupWorker
 * @param timeout
 */
public static void setServerBootstrap(ServerBootstrap bootstrap, EventLoopGroup groupBoss,
        EventLoopGroup groupWorker, int timeout) {
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.group(groupBoss, groupWorker);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    bootstrap.childOption(ChannelOption.TCP_NODELAY, true);
    bootstrap.childOption(ChannelOption.SO_REUSEADDR, true);
    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeout);
    bootstrap.childOption(ChannelOption.SO_RCVBUF, 1048576);
    bootstrap.childOption(ChannelOption.SO_SNDBUF, 1048576);
}

From source file:org.waarp.openr66.protocol.localhandler.LocalTransaction.java

License:Open Source License

/**
 * Constructor/* w w  w.ja  v a2s  . c o  m*/
 */
public LocalTransaction() {
    serverBootstrap.channel(LocalServerChannel.class);
    serverBootstrap.group(Configuration.configuration.getLocalBossGroup(),
            Configuration.configuration.getLocalWorkerGroup());
    serverBootstrap.option(ChannelOption.TCP_NODELAY, true);
    serverBootstrap.option(ChannelOption.SO_REUSEADDR, true);
    serverBootstrap.childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS,
            (int) Configuration.configuration.getTIMEOUTCON());
    serverBootstrap.childHandler(new LocalServerInitializer());
    try {
        serverChannel = serverBootstrap.bind(socketLocalServerAddress).sync().channel();
    } catch (InterruptedException e) {
        throw new IllegalArgumentException(e.getMessage(), e);
    }
    localChannelGroup.add(serverChannel);

    clientBootstrap.channel(LocalChannel.class);
    // Same Group than Network final handler 
    clientBootstrap.group(Configuration.configuration.getLocalWorkerGroup());
    clientBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
            (int) Configuration.configuration.getTIMEOUTCON());
    clientBootstrap.handler(new LocalClientInitializer());
}