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.seagate.kinetic.simulator.io.provider.nio.udt.UdtTransportProvider.java

License:Open Source License

public void doInit() throws InterruptedException {

    this.port = this.service.getServiceConfiguration().getPort();

    final ThreadFactory acceptFactory = new NioThreadFactory("UdtAccept");

    final ThreadFactory connectFactory = new NioThreadFactory("UdtConnect");

    bossGroup = new NioEventLoopGroup(10, acceptFactory, NioUdtProvider.MESSAGE_PROVIDER);

    workerGroup = new NioEventLoopGroup(10, connectFactory, NioUdtProvider.MESSAGE_PROVIDER);

    msChannelInitializer = new UdtChannelInitializer(this.service);

    bootstrap = new ServerBootstrap();

    bootstrap.group(bossGroup, workerGroup).channelFactory(NioUdtProvider.MESSAGE_ACCEPTOR)
            .option(ChannelOption.SO_BACKLOG, 1000).option(ChannelOption.SO_REUSEADDR, true)
            .childHandler(msChannelInitializer);

    logger.info("Kinetic udt service binding on port =" + port);

    channelFuture = bootstrap.bind(port).sync();

    logger.info("Kinetic udt service bound on port =" + port);
}

From source file:com.slyak.services.proxy.server.NettyProxyServer.java

License:Apache License

@SneakyThrows(InterruptedException.class)
public void start() {
    ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.ADVANCED);
    ServerBootstrap bootstrap = new ServerBootstrap();
    bossGroup = new NioEventLoopGroup(proxyProperties.getBoss());
    workerGroup = new NioEventLoopGroup(proxyProperties.getWorker());
    clientGroup = new NioEventLoopGroup(proxyProperties.getClient());
    try {//  w  w w  .j  a v  a 2 s  . c o  m
        bootstrap.group(bossGroup, workerGroup).channel(getChannelClass())
                .option(ChannelOption.SO_BACKLOG, proxyProperties.getBackLog())
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, proxyProperties.getConnectTimeout())

                .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_REUSEADDR, true)

                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        //channel time out handler
                        pipeline.addLast(new IdleStateHandler(0, 0, 30));
                        pipeline.addLast(new IdleEventHandler());
                        //logging
                        pipeline.addLast(new LoggingHandler());

                        if (isRouter()) {
                            pipeline.addLast(getProxyHandler(proxyProperties));
                        } else {
                            pipeline.addLast(getCustomChannelHandlers(clientGroup));
                        }
                        pipeline.addLast(ExceptionHandler.INSTANCE);
                    }
                });
        //start server
        ChannelFuture future = bootstrap.bind(proxyProperties.getPort()).sync();
        log.debug("Starting proxy server , port is {}", proxyProperties.getPort());
        future.channel().closeFuture().sync();
    } finally {
        stop();
    }
}

From source file:com.sohail.alam.http.server.SetupServer.java

License:Apache License

public void initialize() {
    final ServerBootstrap serverBootstrap = new ServerBootstrap();
    final EventLoopGroup boss = new NioEventLoopGroup();
    final EventLoopGroup worker = new NioEventLoopGroup();

    serverBootstrap.group(boss, worker).channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, ServerProperties.PROP.SO_BACKLOG)
            .childOption(ChannelOption.TCP_NODELAY, ServerProperties.PROP.TCP_NODELAY)
            .childOption(ChannelOption.SO_KEEPALIVE, ServerProperties.PROP.SO_KEEPALIVE)
            .childOption(ChannelOption.SO_REUSEADDR, ServerProperties.PROP.SO_REUSEADDR)
            .childHandler(new HttpChannelInitializer());

    try {/*from w  w  w.ja va  2  s.  co  m*/
        ChannelFuture future = serverBootstrap.bind(new InetSocketAddress(ip, port)).sync();
        if (future.isSuccess()) {
            LoggerManager.LOGGER.info("Http Server Started Successfully @ {}:{}", ip, port);
        } else {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
            LoggerManager.LOGGER.fatal("Http Server Start Failed. Can not bind to {}:{}", ip, port);
        }
    } catch (Exception e) {
        LoggerManager.LOGGER.fatal("Exception Caught while starting Http Server", e);
    }

}

From source file:com.streamsets.pipeline.lib.udp.UDPConsumingServer.java

License:Apache License

@Override
protected Bootstrap bootstrap(boolean enableEpoll) {
    if (enableEpoll) {
        // Direct buffers required for Epoll
        enableDirectBuffers();//from  w ww. j  av  a 2 s .co m
        EventLoopGroup group = new EpollEventLoopGroup(numThreads);
        groups.add(group);
        return new Bootstrap().group(group).channel(EpollDatagramChannel.class).handler(handler)
                .option(EpollChannelOption.SO_REUSEADDR, true).option(EpollChannelOption.SO_REUSEPORT, true)
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    } else {
        disableDirectBuffers();
        EventLoopGroup group = new NioEventLoopGroup(numThreads);
        groups.add(group);
        return new Bootstrap().group(group).channel(NioDatagramChannel.class).handler(handler)
                .option(ChannelOption.SO_REUSEADDR, true)
                .option(ChannelOption.ALLOCATOR, new PooledByteBufAllocator()); // use on-heap buffers
    }
}

From source file:com.streamsets.pipeline.stage.origin.udp.UDPConsumingServer.java

License:Apache License

public void listen() throws Exception {
    group = new NioEventLoopGroup();
    for (SocketAddress address : addresses) {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioDatagramChannel.class).handler(new UDPConsumingServerHandler(udpConsumer))
                .option(ChannelOption.SO_REUSEADDR, true)
                .option(ChannelOption.ALLOCATOR, new PooledByteBufAllocator()); // use on-heap buffers
        LOG.info("Starting server on address {}", address);
        ChannelFuture channelFuture = b.bind(address).sync();
        channelFutures.add(channelFuture);
    }//ww  w . j  a  v  a 2 s  .  c  om
}

From source file:com.stremebase.examples.todomvc.Todo.java

License:Apache License

public static void main(String[] args) throws Exception {
    css = new String(Files.readAllBytes(Paths.get(System.getProperty("user.dir"), "Web", "index.css")));
    favicon = Files.readAllBytes(Paths.get(System.getProperty("user.dir"), "Web", "favicon.ico"));

    Table.setDefaultDb(new DB("user.dir"));
    data = new Data(itemTableId, "ITEMTABLE");

    @SuppressWarnings("unchecked")
    Router<Integer> router = new Router<Integer>().GET("/", GET).GET("/filter/:filtertype", FILTER)

            .POST("/", POST).POST("/delete", DELETE).POST("/clearcompleted", DELETECOMPLETED)
            .POST("/toggle-status", TOGGLESTATUS)

            .GET(":something/index.css", CSS).GET("/index.css", CSS).GET("/favicon.ico", ICON)
            .notFound(NOTFOUND);/*from  w w  w  .  ja  va  2 s .  c om*/
    System.out.println(router);

    OioEventLoopGroup bossGroup = new OioEventLoopGroup(1);
    SingleThreadEventLoop workerGroup = new ThreadPerChannelEventLoop(bossGroup);

    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).childOption(ChannelOption.TCP_NODELAY, java.lang.Boolean.TRUE)
                .childOption(ChannelOption.SO_KEEPALIVE, java.lang.Boolean.TRUE)
                .childOption(ChannelOption.SO_REUSEADDR, java.lang.Boolean.TRUE)
                .channel(OioServerSocketChannel.class).childHandler(new HttpRouterServerInitializer(router));

        Channel ch = b.bind(PORT).sync().channel();
        System.out.println("Server started: http://127.0.0.1:" + PORT + '/');

        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.tongbanjie.tarzan.rpc.netty.NettyRpcServer.java

License:Apache License

@Override
public void start() {
    this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(//
            nettyServerConfig.getServerWorkerThreads(), //
            new ThreadFactory() {

                private AtomicInteger threadIndex = new AtomicInteger(0);

                @Override/*from ww  w.j  a  va 2  s.  c o  m*/
                public Thread newThread(Runnable r) {
                    return new Thread(r, "NettyServerCodecThread_" + this.threadIndex.incrementAndGet());
                }
            });

    ServerBootstrap childHandler = //
            this.serverBootstrap.group(this.eventLoopGroupBoss, this.eventLoopGroupSelector)
                    .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, nettyServerConfig.getServerSocketSndBufSize())
                    //
                    .option(ChannelOption.SO_RCVBUF, nettyServerConfig.getServerSocketRcvBufSize())
                    //
                    .localAddress(new InetSocketAddress(this.nettyServerConfig.getListenPort()))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(
                                    //
                                    defaultEventExecutorGroup, //
                                    new NettyEncoder(), //
                                    new NettyDecoder(), //
                                    new IdleStateHandler(0, 0,
                                            nettyServerConfig.getServerChannelMaxIdleTimeSeconds()), //
                                    new NettyConnectManageHandler(), //
                                    new NettyServerHandler());
                        }
                    });

    if (nettyServerConfig.isServerPooledByteBufAllocatorEnable()) {
        childHandler.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    }

    try {
        ChannelFuture sync = this.serverBootstrap.bind().sync();
        InetSocketAddress addr = (InetSocketAddress) sync.channel().localAddress();
        this.port = addr.getPort();
    } catch (InterruptedException e1) {
        throw new RuntimeException("this.serverBootstrap.bind().sync() InterruptedException", e1);
    }

    if (this.channelEventListener != null) {
        this.nettyEventExecutor.start();
    }

    this.timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            try {
                NettyRpcServer.this.scanResponseTable();
            } catch (Exception e) {
                LOGGER.error("scanResponseTable exception", e);
            }
        }
    }, 1000 * 3, 1000);

    LOGGER.info("Rpc server [port:{}] start success", port);
}

From source file:com.turn.ttorrent.client.io.PeerClient.java

License:Apache License

public void start() throws Exception {
    bootstrap = new Bootstrap();
    bootstrap.group(environment.getEventService());
    bootstrap.channel(environment.getEventLoopType().getClientChannelType());
    // SocketAddress address = environment.getLocalPeerListenAddress();
    // if (address != null) bootstrap.localAddress(address);
    bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    // bootstrap.option(ChannelOption.SO_TIMEOUT, (int) TimeUnit.MINUTES.toMillis(CLIENT_KEEP_ALIVE_MINUTES));
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) TimeUnit.SECONDS.toMillis(10));
    // TODO: Derive from PieceHandler.DEFAULT_BLOCK_SIZE
    // bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 1024 * 1024);
    // bootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
}

From source file:com.turn.ttorrent.client.io.PeerServer.java

License:Apache License

/**
 * Create and start a new listening service for our torrents, reporting
 * with our peer ID on the given address.
 *
 * <p>/*w w  w  .j a v  a 2s .  c o m*/
 * This binds to the first available port in the client port range
 * PORT_RANGE_START to PORT_RANGE_END.
 * </p>
 */
public void start() throws Exception {
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(environment.getEventService());
    bootstrap.channel(environment.getEventLoopType().getServerChannelType());
    bootstrap.option(ChannelOption.SO_BACKLOG, 128);
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.childHandler(new ChannelInitializer() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.pipeline().addLast(new PeerServerHandshakeHandler(torrents));
        }
    });
    bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
    // bootstrap.childOption(ChannelOption.SO_TIMEOUT, (int) TimeUnit.MINUTES.toMillis(CLIENT_KEEP_ALIVE_MINUTES));
    // TODO: Derive from PieceHandler.DEFAULT_BLOCK_SIZE
    // bootstrap.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 1024 * 1024);
    // bootstrap.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
    SocketAddress address = environment.getLocalPeerListenAddress();
    if (address != null) {
        future = bootstrap.bind(address).sync();
    } else {
        BIND: {
            Exception x = new IOException("No available port for the BitTorrent client!");
            for (int i = PORT_RANGE_START; i <= PORT_RANGE_END; i++) {
                try {
                    future = bootstrap.bind(i).sync();
                    break BIND;
                } catch (InterruptedException e) {
                    throw e;
                } catch (Exception e) {
                    x = e;
                }
            }
            throw new IOException("Failed to find an address to bind in range [" + PORT_RANGE_START + ","
                    + PORT_RANGE_END + "]", x);
        }
    }
}

From source file:com.twocater.diamond.core.netty.NettyConnector.java

@Override
public void bind() throws Exception {
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();

    serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(bossGroup, workerGroup);
    ChannelHandlerAdapter serverHandler = this.nettyHandlerFactory.createServerHandler();
    if (serverHandler != null) {
        serverBootstrap.handler(serverHandler);
    }// w  w  w. jav  a2s.c  o m
    serverBootstrap.channel(NioServerSocketChannel.class);
    serverBootstrap.childHandler(this.nettyHandlerFactory.createChildHandler(connectorConfig.getTimeout()));

    serverBootstrap.option(ChannelOption.SO_BACKLOG, connectorConfig.getSo_backlog_parent());
    serverBootstrap.option(ChannelOption.SO_REUSEADDR, connectorConfig.isSo_reuseaddr_parent());

    //         serverBootstrap.childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000);//??? netty
    //        serverBootstrap.childOption(ChannelOption.SO_TIMEOUT, 5000);//??? ?timeout??
    serverBootstrap.childOption(ChannelOption.TCP_NODELAY, connectorConfig.isTcp_nodelay());
    serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, connectorConfig.isKeepAlive());

    serverBootstrap.childOption(ChannelOption.SO_REUSEADDR, connectorConfig.isSo_reuseaddr());
    serverBootstrap.childOption(ChannelOption.SO_LINGER, connectorConfig.getSo_linger());
    serverBootstrap.childOption(ChannelOption.SO_SNDBUF, connectorConfig.getSo_sndbuf());
    serverBootstrap.childOption(ChannelOption.SO_RCVBUF, connectorConfig.getSo_rcvbuf());

    channelFuture = serverBootstrap.bind(connectorConfig.getPort()).sync();
}