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:io.vertx.core.net.impl.transport.Transport.java

License:Open Source License

public void configure(ClientOptionsBase options, Bootstrap bootstrap) {
    if (options.getLocalAddress() != null) {
        bootstrap.localAddress(options.getLocalAddress(), 0);
    }/*from  ww w . j  a  v  a2s . co  m*/
    bootstrap.option(ChannelOption.TCP_NODELAY, options.isTcpNoDelay());
    if (options.getSendBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, options.getSendBufferSize());
    }
    if (options.getReceiveBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, options.getReceiveBufferSize());
        bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR,
                new FixedRecvByteBufAllocator(options.getReceiveBufferSize()));
    }
    if (options.getSoLinger() != -1) {
        bootstrap.option(ChannelOption.SO_LINGER, options.getSoLinger());
    }
    if (options.getTrafficClass() != -1) {
        bootstrap.option(ChannelOption.IP_TOS, options.getTrafficClass());
    }
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, options.getConnectTimeout());
    bootstrap.option(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, options.isTcpKeepAlive());
    bootstrap.option(ChannelOption.SO_REUSEADDR, options.isReuseAddress());
}

From source file:io.vertx.core.net.impl.transport.Transport.java

License:Open Source License

public void configure(NetServerOptions options, ServerBootstrap bootstrap) {
    bootstrap.childOption(ChannelOption.TCP_NODELAY, options.isTcpNoDelay());
    if (options.getSendBufferSize() != -1) {
        bootstrap.childOption(ChannelOption.SO_SNDBUF, options.getSendBufferSize());
    }/*w w w  .  ja  v  a 2 s.  c  o m*/
    if (options.getReceiveBufferSize() != -1) {
        bootstrap.childOption(ChannelOption.SO_RCVBUF, options.getReceiveBufferSize());
        bootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR,
                new FixedRecvByteBufAllocator(options.getReceiveBufferSize()));
    }
    if (options.getSoLinger() != -1) {
        bootstrap.childOption(ChannelOption.SO_LINGER, options.getSoLinger());
    }
    if (options.getTrafficClass() != -1) {
        bootstrap.childOption(ChannelOption.IP_TOS, options.getTrafficClass());
    }
    bootstrap.childOption(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);
    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, options.isTcpKeepAlive());
    bootstrap.option(ChannelOption.SO_REUSEADDR, options.isReuseAddress());
    if (options.getAcceptBacklog() != -1) {
        bootstrap.option(ChannelOption.SO_BACKLOG, options.getAcceptBacklog());
    }
}

From source file:jj.http.server.HttpServer.java

License:Apache License

private void makeServerBootstrap(int bindingCount) {
    serverBootstrap = new ServerBootstrap()
            .group(new NioEventLoopGroup(bindingCount, threadFactory), ioEventLoopGroup)
            .channel(NioServerSocketChannel.class).childHandler(initializer)
            .option(ChannelOption.SO_KEEPALIVE, configuration.keepAlive())
            .option(ChannelOption.SO_REUSEADDR, configuration.reuseAddress())
            .option(ChannelOption.TCP_NODELAY, configuration.tcpNoDelay())
            .option(ChannelOption.SO_TIMEOUT, configuration.timeout())
            .option(ChannelOption.SO_BACKLOG, configuration.backlog())
            .option(ChannelOption.SO_RCVBUF, configuration.receiveBufferSize())
            .option(ChannelOption.SO_SNDBUF, configuration.sendBufferSize());
}

From source file:net.kuujo.copycat.io.transport.NettyServer.java

License:Apache License

/**
 * Starts listening for the given member.
 *///from  ww  w. j a v a2  s  .c  o  m
private void listen(Address address, Consumer<Connection> listener, Context context) {
    channelGroup = new DefaultChannelGroup("copycat-acceptor-channels", GlobalEventExecutor.INSTANCE);

    handler = new ServerHandler(connections, listener, context);

    final ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(eventLoopGroup)
            .channel(eventLoopGroup instanceof EpollEventLoopGroup ? EpollServerSocketChannel.class
                    : NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel channel) throws Exception {
                    ChannelPipeline pipeline = channel.pipeline();
                    pipeline.addLast(FIELD_PREPENDER);
                    pipeline.addLast(new LengthFieldBasedFrameDecoder(1024 * 32, 0, 2, 0, 2));
                    pipeline.addLast(handler);
                }
            }).option(ChannelOption.SO_BACKLOG, 128).option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.ALLOCATOR, ALLOCATOR)
            .childOption(ChannelOption.SO_KEEPALIVE, true);

    LOGGER.info("Binding to {}", address);

    ChannelFuture bindFuture = bootstrap.bind(address.socketAddress());
    bindFuture.addListener((ChannelFutureListener) channelFuture -> {
        if (channelFuture.isSuccess()) {
            listening = true;
            context.executor().execute(() -> {
                LOGGER.info("Listening at {}", bindFuture.channel().localAddress());
                listenFuture.complete(null);
            });
        } else {
            context.execute(() -> listenFuture.completeExceptionally(channelFuture.cause()));
        }
    });
    channelGroup.add(bindFuture.channel());
}

From source file:net.kuujo.copycat.netty.NettyTcpProtocolServer.java

License:Apache License

@Override
public synchronized CompletableFuture<Void> listen() {
    final CompletableFuture<Void> future = new CompletableFuture<>();

    final SslContext sslContext;
    if (protocol.isSsl()) {
        try {/*from  w ww  .ja  va 2s  . com*/
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslContext = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
        } catch (SSLException | CertificateException e) {
            future.completeExceptionally(e);
            return future;
        }
    } else {
        sslContext = null;
    }

    serverGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup(protocol.getThreads());

    final ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(serverGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel channel) throws Exception {
                    ChannelPipeline pipeline = channel.pipeline();
                    if (sslContext != null) {
                        pipeline.addLast(sslContext.newHandler(channel.alloc()));
                    }
                    pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4));
                    pipeline.addLast("bytesDecoder", new ByteArrayDecoder());
                    pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
                    pipeline.addLast("bytesEncoder", new ByteArrayEncoder());
                    pipeline.addLast("handler", new ServerHandler());
                }
            }).option(ChannelOption.SO_BACKLOG, 128);

    if (protocol.getSendBufferSize() > -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, protocol.getSendBufferSize());
    }

    if (protocol.getReceiveBufferSize() > -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, protocol.getReceiveBufferSize());
    }

    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.SO_BACKLOG, protocol.getAcceptBacklog());

    if (protocol.getTrafficClass() > -1) {
        bootstrap.option(ChannelOption.IP_TOS, protocol.getTrafficClass());
    }

    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);

    // Bind and start to accept incoming connections.
    bootstrap.bind(host, port).addListener((ChannelFutureListener) channelFuture -> {
        channelFuture.channel().closeFuture().addListener(closeFuture -> {
            workerGroup.shutdownGracefully();
        });

        if (channelFuture.isSuccess()) {
            channel = channelFuture.channel();
            future.complete(null);
        } else {
            future.completeExceptionally(channelFuture.cause());
        }
    });
    return future;
}

From source file:net.kuujo.copycat.netty.protocol.impl.TcpProtocolServer.java

License:Apache License

@Override
public CompletableFuture<Void> start() {
    final CompletableFuture<Void> future = new CompletableFuture<>();

    // TODO: Configure proper SSL trust store.
    final SslContext sslContext;
    if (protocol.isSsl()) {
        try {//from  w  w w.  ja v a2 s  .  co m
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslContext = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
        } catch (SSLException | CertificateException e) {
            future.completeExceptionally(e);
            return future;
        }
    } else {
        sslContext = null;
    }

    final EventLoopGroup serverGroup = new NioEventLoopGroup();
    final EventLoopGroup workerGroup = new NioEventLoopGroup(protocol.getThreads());

    final ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(serverGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel channel) throws Exception {
                    ChannelPipeline pipeline = channel.pipeline();
                    if (sslContext != null) {
                        pipeline.addLast(sslContext.newHandler(channel.alloc()));
                    }
                    pipeline.addLast(new ObjectEncoder(),
                            new ObjectDecoder(
                                    ClassResolvers.softCachingConcurrentResolver(getClass().getClassLoader())),
                            new TcpProtocolServerHandler(TcpProtocolServer.this));
                }
            }).option(ChannelOption.SO_BACKLOG, 128);

    if (protocol.getSendBufferSize() > -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, protocol.getSendBufferSize());
    }

    if (protocol.getReceiveBufferSize() > -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, protocol.getReceiveBufferSize());
    }

    bootstrap.option(ChannelOption.TCP_NODELAY, protocol.isNoDelay());
    bootstrap.option(ChannelOption.SO_REUSEADDR, protocol.isReuseAddress());
    bootstrap.option(ChannelOption.SO_KEEPALIVE, protocol.isKeepAlive());
    bootstrap.option(ChannelOption.SO_BACKLOG, protocol.getAcceptBacklog());

    if (protocol.getTrafficClass() > -1) {
        bootstrap.option(ChannelOption.IP_TOS, protocol.getTrafficClass());
    }

    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);

    // Bind and start to accept incoming connections.
    bootstrap.bind(protocol.getHost(), protocol.getPort()).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture channelFuture) throws Exception {
            channelFuture.channel().closeFuture().addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    workerGroup.shutdownGracefully();
                }
            });

            if (channelFuture.isSuccess()) {
                channel = channelFuture.channel();
                future.complete(null);
            } else {
                future.completeExceptionally(channelFuture.cause());
            }
        }
    });
    return future;
}

From source file:net.marfgamer.jraknet.client.RakNetClient.java

License:Open Source License

/**
 * Constructs a <code>RakNetClient</code> with the specified
 * <code>DiscoveryMode</code> and server discovery port.
 * //from   w  w  w  . j av  a 2  s. c  om
 * @param discoveryMode
 *            how the client will discover servers. If this is set to
 *            <code>null</code>, the client will enable set it to
 *            <code>DiscoveryMode.ALL_CONNECTIONS</code> as long as the port
 *            is greater than -1.
 * @param discoveryPorts
 *            the ports the client will attempt to discover servers on.
 */
public RakNetClient(DiscoveryMode discoveryMode, int... discoveryPorts) {
    // Set client data
    UUID uuid = UUID.randomUUID();
    this.guid = uuid.getMostSignificantBits();
    this.pingId = uuid.getLeastSignificantBits();
    this.timestamp = System.currentTimeMillis();

    // Set discovery data
    this.discoveryPorts = new HashSet<Integer>();
    this.discoveryMode = discoveryMode;
    this.setDiscoveryPorts(discoveryPorts);
    if (discoveryMode == null) {
        this.discoveryMode = (discoveryPorts.length > 0 ? DiscoveryMode.ALL_CONNECTIONS : DiscoveryMode.NONE);
    }
    this.discovered = new ConcurrentHashMap<InetSocketAddress, DiscoveredServer>();
    this.externalServers = new ConcurrentHashMap<InetSocketAddress, DiscoveredServer>();

    // Set networking data
    this.bootstrap = new Bootstrap();
    this.group = new NioEventLoopGroup();
    this.handler = new RakNetClientHandler(this);

    // Add maximum transfer units
    this.maximumTransferUnits = new IntMap<MaximumTransferUnit>();
    MaximumTransferUnit firstTransferUnit = new MaximumTransferUnit(1464, 3);
    if (RakNetUtils.getMaximumTransferUnit() >= firstTransferUnit.getMaximumTransferUnit()) {
        this.addMaximumTransferUnit(new MaximumTransferUnit(RakNetUtils.getMaximumTransferUnit(), 2));
    }
    this.addMaximumTransferUnit(firstTransferUnit);
    this.addMaximumTransferUnit(new MaximumTransferUnit(1172, 4));
    this.addMaximumTransferUnit(new MaximumTransferUnit(RakNet.MINIMUM_TRANSFER_UNIT, 5));

    // Initiate bootstrap data
    try {
        bootstrap.channel(NioDatagramChannel.class).group(group).handler(handler);
        bootstrap.option(ChannelOption.SO_BROADCAST, true).option(ChannelOption.SO_REUSEADDR, false);
        this.channel = bootstrap.bind(0).sync().channel();
        RakNetLogger.debug(this, "Created and bound bootstrap");
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:net.marfgamer.jraknet.server.RakNetServer.java

License:Open Source License

/**
 * Starts the server.//from  w ww.ja v a  2  s  .c  o m
 * 
 * @throws NoListenerException
 *             if the listener has not yet been set.
 */
public final void start() throws NoListenerException {
    // Make sure we have an adapter
    if (listener == null) {
        throw new NoListenerException();
    }

    // Create bootstrap and bind the channel
    try {
        bootstrap.channel(NioDatagramChannel.class).group(group).handler(handler);
        bootstrap.option(ChannelOption.SO_BROADCAST, true).option(ChannelOption.SO_REUSEADDR, false);
        this.channel = bootstrap.bind(port).sync().channel();
        this.running = true;
        RakNetLogger.debug(this, "Created and bound bootstrap");
    } catch (InterruptedException e) {
        e.printStackTrace();
        this.running = false;
    }

    // Notify API
    RakNetLogger.info(this, "Started server");
    listener.onServerStart();

    // Update system
    while (this.running == true) {
        if (sessions.size() <= 0) {
            continue; // Do not loop through non-existent sessions
        }
        synchronized (sessions) {
            for (RakNetClientSession session : sessions.values()) {
                try {
                    // Update session and make sure it isn't DOSing us
                    session.update();
                    if (session.getPacketsReceivedThisSecond() >= RakNet.getMaxPacketsPerSecond()) {
                        this.blockAddress(session.getInetAddress(), "Too many packets",
                                RakNet.MAX_PACKETS_PER_SECOND_BLOCK);
                    }
                } catch (Throwable throwable) {
                    // An error related to the session occurred, remove it
                    listener.onSessionException(session, throwable);
                    this.removeSession(session, throwable.getMessage());
                }
            }
        }
    }
}

From source file:net.NettyEngine4.ServerServiceImpl.java

License:Apache License

/**
 *  run netty server//from  w  ww .  j a v a 2s  .  co  m
 *  NioEventLoopGroup used for NIO Selector based Channels
 *  two NioEventLoopGroup(AioEventLoopGroup) will be used. The first is
 *  used to handle the accept of new connections and the second will serve the IO of them.
 *  IoEventLoopGroupThread +1;
 *  DefaultEventExecutorGroup ?
 *
 *  bossExecutor:?SocketChannel
 *  workerExecutorSocketChannel?channel/
 *  executionLogicHandlerThread????
 *  AIO ?channelgroup?group?
 *  option() is for the NioServerSocketChannel that accepts incoming connections
 *  childOption() is for the Channels accepted by the parent ServerChannel,
 *  which is NioServerSocketChannel in this case.
 *
 *   ServerBootstrap ?? parent channel
 *   parent channel ? connections
 *  ? connection ? child channel ??
 */
@Override
public void run() throws Exception {
    NioEventLoopGroup EventLoopGroupLister = new NioEventLoopGroup(0x1,
            new PriorityThreadFactory("@+main_reactor+@", Thread.NORM_PRIORITY));
    NioEventLoopGroup IOEventLoopGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() + 1,
            new PriorityThreadFactory("@+sub_reactor+@", Thread.NORM_PRIORITY));
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    try {
        serverBootstrap.group(EventLoopGroupLister, IOEventLoopGroup).channel(NioServerSocketChannel.class)
                .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.SO_REUSEADDR, true) //??
                .childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(false))// heap buf 's better
                .childOption(ChannelOption.SO_RCVBUF, 1048576).childOption(ChannelOption.SO_SNDBUF, 1048576)
                .childHandler(new ServerChannelInitializer());//used to serve the request for the {@link Channel}'s
        // Bind and start to accept incoming connections.
        ChannelFuture channelFuture = serverBootstrap
                .bind(new InetSocketAddress(Config.DEFAULT_VALUE.SERVER_VALUE.gameserverPort)).sync();
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("server??:" + Config.DEFAULT_VALUE.SERVER_VALUE.gameserverPort);
        // Wait until the server socket is closed.
        // In this server, this does not happen, but you can do that to gracefully
        // shut down your server.
        channelFuture.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        EventLoopGroupLister.shutdownGracefully();
        IOEventLoopGroup.shutdownGracefully();
    }
}

From source file:net.NettyEngine4.ServerServiceImpl.java

License:Apache License

/**
 * jni native Epoll/*w ww  .  j  a  va2s  . c  om*/
 #NioEventLoopGroup  EpollEventLoopGroup   ---- EventLoopGroup ?
 #NioEventLoop  EpollEventLoop
 #NioServerSocketChannel  EpollServerSocketChannel
 #NioSocketChannel  EpollSocketChannel        ---- SocketChannel?
        
 ## RHEL/CentOS/Fedora:
 #sudo yum install autoconf automake libtool glibc-devel.i686 glibc-devel libgcc.i686 make
 ## Debian/Ubuntu:
 #sudo apt-get install autoconf automake libtool make gcc-multilib
 * @throws Exception
 */
@Override
public void runNativeEpoll() throws Exception {
    EpollEventLoopGroup BossEventLoopGroup = new EpollEventLoopGroup(0x1,
            new PriorityThreadFactory("@+?", Thread.NORM_PRIORITY)); //mainReactor    1
    EpollEventLoopGroup WorkerEventLoopGroup = new EpollEventLoopGroup(
            Runtime.getRuntime().availableProcessors() + 0x1,
            new PriorityThreadFactory("@+I/O", Thread.NORM_PRIORITY)); //subReactor       ?cpu+1
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    try {
        serverBootstrap.group(BossEventLoopGroup, WorkerEventLoopGroup).channel(EpollServerSocketChannel.class)
                .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.SO_REUSEADDR, true) //??
                .childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(false))// heap buf 's better
                .childOption(ChannelOption.SO_RCVBUF, 1048576).childOption(ChannelOption.SO_SNDBUF, 1048576)
                .childHandler(new ServerChannelInitializer());//used to serve the request for the {@link Channel}'s
        // Bind and start to accept incoming connections.
        ChannelFuture channelFuture = serverBootstrap
                .bind(new InetSocketAddress(Config.DEFAULT_VALUE.SERVER_VALUE.gameserverPort)).sync();
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("server??:" + Config.DEFAULT_VALUE.SERVER_VALUE.gameserverPort);
        // Wait until the server socket is closed.
        // In this server, this does not happen, but you can do that to gracefully
        // shut down your server.
        channelFuture.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        BossEventLoopGroup.shutdownGracefully();
        WorkerEventLoopGroup.shutdownGracefully();
    }
}