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.alibaba.rocketmq.remoting.netty.NettyRemotingServer.java

License:Apache License

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

                private AtomicInteger threadIndex = new AtomicInteger(0);

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

    ServerBootstrap childHandler = //
            this.serverBootstrap.group(this.eventLoopGroupBoss, this.eventLoopGroupWorker);
    if (isLinux) {
        childHandler.channel(EpollServerSocketChannel.class);
    } else {
        childHandler.channel(NioServerSocketChannel.class);
    }
    if (isLinux) {
        childHandler.option(EpollChannelOption.SO_REUSEPORT, true);
    }
    //
    childHandler.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 NettyConnetManageHandler(), //
                            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.nettyEventExecuter.start();
    }

    // ?1??
    this.timer.scheduleAtFixedRate(new TimerTask() {

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

From source file:com.alibaba.rocketmq.remoting.netty.NettyUDPServer.java

License:Apache License

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

                private AtomicInteger threadIndex = new AtomicInteger(0);

                @Override/*  w  ww. j av a2 s .  c  o m*/
                public Thread newThread(Runnable r) {
                    return new Thread(r, "NettyServerWorkerThread_" + this.threadIndex.incrementAndGet());
                }
            });

    Bootstrap childHandler = //
            this.serverBootstrap.group(this.eventLoopGroupWorker).channel(NioDatagramChannel.class)
                    //
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    //
                    .option(ChannelOption.SO_REUSEADDR, true)
                    //
                    .option(ChannelOption.SO_KEEPALIVE, false)
                    //
                    .option(ChannelOption.SO_BROADCAST, true)
                    //
                    .option(ChannelOption.SO_SNDBUF, nettyServerConfig.getServerSocketSndBufSize())
                    //
                    .option(ChannelOption.SO_RCVBUF, nettyServerConfig.getServerSocketRcvBufSize())
                    //
                    .localAddress(new InetSocketAddress(this.nettyServerConfig.getListenUDPPort()))
                    .handler(new ChannelInitializer<DatagramChannel>() {
                        @Override
                        public void initChannel(DatagramChannel ch) throws Exception {
                            ch.pipeline().addLast(
                                    //
                                    defaultEventExecutorGroup, //
                                    new UDP2BufAdapt(), new NettyEncoder(), //
                                    //
                                    //new IdleStateHandler(0, 0, nettyServerConfig.getServerChannelMaxIdleTimeSeconds()),//
                                    //new NettyConnetManageHandler(), //
                                    new NettyServerHandler());
                        }
                    });

    if (nettyServerConfig.isServerPooledByteBufAllocatorEnable()) {
        // ????
        childHandler.option(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.nettyEventExecuter.start();
    }

    // ?1??
    this.timer.scheduleAtFixedRate(new TimerTask() {

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

From source file:com.ancun.netty.httpserver.HttpServer.java

License:Apache License

private void setBootstrapOptions(ServerBootstrap bootstrap) {
    bootstrap.option(ChannelOption.SO_KEEPALIVE, useKeepAlive());
    bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
    bootstrap.option(ChannelOption.TCP_NODELAY, useTcpNoDelay());
    bootstrap.option(ChannelOption.SO_KEEPALIVE, serverSettings.isKeepAlive());
    bootstrap.option(ChannelOption.SO_REUSEADDR, shouldReuseAddress());
    bootstrap.option(ChannelOption.SO_LINGER, getSoLinger());
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getConnectTimeoutMillis());
    bootstrap.option(ChannelOption.SO_RCVBUF, getReceiveBufferSize());
    bootstrap.option(ChannelOption.MAX_MESSAGES_PER_READ, Integer.MAX_VALUE);

    bootstrap.childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(true));
    bootstrap.childOption(ChannelOption.MAX_MESSAGES_PER_READ, Integer.MAX_VALUE);
    bootstrap.childOption(ChannelOption.SO_RCVBUF, getReceiveBufferSize());
    bootstrap.childOption(ChannelOption.SO_REUSEADDR, shouldReuseAddress());
}

From source file:com.andrewkroh.cicso.rtp.NettyRtpSession.java

License:Apache License

public NettyRtpSession(final InetSocketAddress bindAddress, final NetworkInterface multicastInterface,
        final InetAddress multicastGroup) {
    Preconditions.checkNotNull(bindAddress, "Must specify a bind address.");

    if (multicastGroup != null) {
        Preconditions.checkNotNull(multicastInterface,
                "When specifying the multicast group you must also " + "specify the multicast interface.");

        // Javadoc for Java 7 MulticastChannel states: The channel's
        // socket should be bound to the wildcard address. If the socket
        // is bound to a specific address, rather than the wildcard address
        // then it is implementation specific if multicast datagrams
        // are received by the socket.
        Preconditions.checkArgument(bindAddress.getAddress().isAnyLocalAddress(),
                "Must bind to wildcard address when using multicast.");
    }/*  ww w . jav  a 2  s.  c o m*/

    EventLoopGroup workerGroup = new NioEventLoopGroup(NUM_THREADS);

    bootstrap = new Bootstrap();
    bootstrap.group(workerGroup).channel(NioDatagramChannel.class).option(ChannelOption.SO_REUSEADDR, true)
            .localAddress(bindAddress).handler(new ChannelInitializer<Channel>() {
                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ch.pipeline().addLast(new RtpPacketHandler(NettyRtpSession.this));
                }
            });

    if (multicastGroup != null) {
        bootstrap.option(ChannelOption.IP_MULTICAST_TTL, MULTICAST_TTL);

        // All multicast traffic generated from this channel will be
        // output from this interface. If not specified it will use the OS
        // default which may be unpredicatable:
        bootstrap.option(ChannelOption.IP_MULTICAST_IF, multicastInterface);
    }

    channel = (DatagramChannel) bootstrap.bind().syncUninterruptibly().channel();

    LOGGER.info("Session bound to: {}", channel.localAddress());

    if (multicastGroup != null) {
        channel.joinGroup(multicastGroup, multicastInterface, null).syncUninterruptibly();

        LOGGER.info("Session bound to multicast group {} on interface {}.", multicastGroup.getHostAddress(),
                multicastInterface.getDisplayName());
    } else {
        LOGGER.info("Session will not be a multicast listener because " + "no multicast group was specified.");
    }
}

From source file:com.andrewkroh.cisco.rtp.NettyRtpSessionTest.java

License:Apache License

/**
 * Creates the test client and binds it to a random IPv4 address.
 *//*w  w w. j  av a 2  s .c  o  m*/
@Before
public void beforeTest() throws InterruptedException, UnknownHostException {
    clientHandler = new TestHandler();
    clientBootstrap = new Bootstrap();
    clientBootstrap.group(new NioEventLoopGroup()).channel(NioDatagramChannel.class)
            .option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.IP_MULTICAST_IF, multicastInterface)
            .localAddress(TestUtils.getFreePort()).handler(clientHandler);

    clientChannel = (DatagramChannel) clientBootstrap.bind().sync().channel();

    rtpPacket = new RtpPacket();
    rtpPacket.setPayloadType(PAYLOAD_TYPE);
    rtpPacket.setRtpPayloadData(new byte[] { PACKET_PAYLOAD_DATA });
    rtpPacket.setTimestamp(TIMESTAMP);
}

From source file:com.avanza.astrix.netty.server.NettyRemotingServer.java

License:Apache License

public void start() {
    bossGroup = new NioEventLoopGroup(1);
    workerGroup = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_REUSEADDR, false).handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override/*from w ww. j av  a2s . c om*/
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(new ObjectEncoder(), new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                            new NettyRemotingServerHandler(serviceActivator));
                }
            });

    // Bind and start to accept incoming connections. Binds to all interfaces
    // TODO: Allow specifying a bind port range. Attempt to bind to each port in range and use first successfully bound port
    ChannelFuture channel = b.bind(port);
    try {
        if (channel.await(2, TimeUnit.SECONDS)) {
            if (channel.isSuccess()) {
                port = InetSocketAddress.class.cast(channel.channel().localAddress()).getPort();
                log.info("NettyRemotingServer started listening on port={}", port);
                return;
            }
        }
    } catch (InterruptedException e) {
    }
    throw new IllegalStateException("Failed to start netty remoting server. Can't bind to port: " + port);
}

From source file:com.baidu.jprotobuf.pbrpc.transport.RpcClient.java

License:Apache License

public RpcClient(Class<? extends Channel> clientChannelClass, RpcClientOptions rpcClientOptions) {
    this.workerGroup = new NioEventLoopGroup();
    this.group(workerGroup);
    this.channel(clientChannelClass);
    this.handler(new RpcClientPipelineinitializer(this));
    this.rpcClientOptions = rpcClientOptions;
    this.option(ChannelOption.SO_REUSEADDR, rpcClientOptions.isReuseAddress());
    this.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, rpcClientOptions.getConnectTimeout());
    this.option(ChannelOption.SO_SNDBUF, rpcClientOptions.getSendBufferSize());
    this.option(ChannelOption.SO_RCVBUF, rpcClientOptions.getSendBufferSize());
    this.option(ChannelOption.SO_KEEPALIVE, rpcClientOptions.isKeepAlive());
    this.option(ChannelOption.TCP_NODELAY, rpcClientOptions.getTcpNoDelay());
    this.option(ChannelOption.MESSAGE_SIZE_ESTIMATOR,
            new DefaultMessageSizeEstimator(rpcClientOptions.getReceiveBufferSize()));

    // add count/*from   w w  w  . j  ava  2  s.co  m*/
    INSTANCE_COUNT.incrementAndGet();
}

From source file:com.baidu.jprotobuf.pbrpc.transport.RpcServer.java

License:Apache License

public RpcServer(Class<? extends ServerChannel> serverChannelClass, RpcServerOptions serverOptions,
        RpcServiceRegistry rpcServiceRegistry) {
    if (rpcServiceRegistry == null) {
        throw new RuntimeException("protperty 'rpcServiceRegistry ' is null.");
    }/* w  w  w . jav a 2s  .  c  o m*/

    if (serverOptions == null) {
        serverOptions = new RpcServerOptions();
    }

    this.bossGroup = new NioEventLoopGroup(serverOptions.getAcceptorThreads());
    this.workerGroup = new NioEventLoopGroup(serverOptions.getWorkThreads());
    this.group(this.bossGroup, this.workerGroup);
    this.channel(serverChannelClass);

    this.option(ChannelOption.SO_BACKLOG, serverOptions.getBacklog());

    this.childOption(ChannelOption.SO_KEEPALIVE, serverOptions.isKeepAlive());
    this.childOption(ChannelOption.SO_REUSEADDR, true);
    this.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    this.childOption(ChannelOption.TCP_NODELAY, serverOptions.isTcpNoDelay());
    this.childOption(ChannelOption.SO_LINGER, serverOptions.getSoLinger());
    this.childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, serverOptions.getConnectTimeout());
    this.childOption(ChannelOption.SO_RCVBUF, serverOptions.getReceiveBufferSize());
    this.childOption(ChannelOption.SO_SNDBUF, serverOptions.getSendBufferSize());

    this.rpcServiceRegistry = rpcServiceRegistry;
    // do register meta service
    rpcServiceRegistry.doRegisterMetaService();
    this.rpcServerOptions = serverOptions;
    this.rpcServerPipelineInitializer = new RpcServerPipelineInitializer(rpcServiceRegistry, rpcServerOptions);
    this.childHandler(rpcServerPipelineInitializer);
}

From source file:com.barchart.http.server.HttpServer.java

License:BSD License

/**
 * Start the server with the configuration settings provided.
 *///from  ww  w .jav a2 s. c  o m
public ChannelFuture listen() {

    if (config == null) {
        throw new IllegalStateException("Server has not been configured");
    }

    if (serverChannel != null) {
        throw new IllegalStateException("Server is already running.");
    }

    final ChannelFuture future = new ServerBootstrap() //
            .group(config.parentGroup(), config.childGroup()) //
            .channel(NioServerSocketChannel.class) //
            .localAddress(config.address()) //
            .childHandler(new HttpServerChannelInitializer()) //
            .option(ChannelOption.SO_REUSEADDR, true) //
            .option(ChannelOption.SO_SNDBUF, 262144) //
            .option(ChannelOption.SO_RCVBUF, 262144) //
            .bind();

    serverChannel = future.channel();

    return future;

}

From source file:com.barchart.netty.server.base.AbstractStatefulServer.java

License:BSD License

@Override
protected ServerBootstrap bootstrap() {

    final ServerBootstrap bootstrap = new ServerBootstrap() //
            .group(defaultGroup, childGroup) //
            .channel(channelType) //
            .childHandler(new ServerChannelInitializer()) //
            .option(ChannelOption.SO_REUSEADDR, true) //
            .option(ChannelOption.SO_SNDBUF, 262144) //
            .option(ChannelOption.SO_RCVBUF, 262144) //
            .childOption(ChannelOption.SO_SNDBUF, 262144) //
            .childOption(ChannelOption.SO_RCVBUF, 262144);

    if (bootstrapInit != null) {
        bootstrapInit.initBootstrap(bootstrap);
    }//www .ja  v  a2  s  . c  om

    return bootstrap;

}