Example usage for io.netty.channel ChannelOption SO_SNDBUF

List of usage examples for io.netty.channel ChannelOption SO_SNDBUF

Introduction

In this page you can find the example usage for io.netty.channel ChannelOption SO_SNDBUF.

Prototype

ChannelOption SO_SNDBUF

To view the source code for io.netty.channel ChannelOption SO_SNDBUF.

Click Source Link

Usage

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);
    }//from ww w  . ja v  a2  s.com
    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();
}

From source file:com.vela.iot.active.netty.coap.CoAPClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    int bossCount = 1;
    if (args.length > 3) {
        bossCount = Integer.parseInt(args[3]);
    }/*from   w w w .  j a  v a2s . com*/
    int bufSize = 655350;
    if (args.length > 4) {
        bufSize = Integer.parseInt(args[4]);
    }
    EventLoopGroup group = new NioEventLoopGroup(bossCount);
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_RCVBUF, bufSize)
                .option(ChannelOption.SO_SNDBUF, bufSize).handler(new CoAPClientHandler());
        Channel ch = b.bind(0).sync().channel();
        String ip = "192.168.2.185";
        if (args.length > 0) {
            ip = args[0];
        }
        if (args.length > 1) {
            REQ_NUM = Integer.parseInt(args[1]);
        }
        int concNum = 10;
        if (args.length > 2) {
            concNum = Integer.parseInt(args[2]);
        }
        InetSocketAddress add = new InetSocketAddress(ip, PORT);

        long start = System.nanoTime();
        ch.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("start", CharsetUtil.UTF_8), add));
        for (int i = 0; i < REQ_NUM; i++) {
            ch.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(
                    "auth/gw/active?devSn=wZud4fM6SUuvvvBoFyGNYw&devKey=8I8LLGb7QaOZw6wgYInDrQ&devInfo=" + i,
                    CharsetUtil.UTF_8), add));
            if (i % concNum == 0)
                Thread.sleep(0, 1);
        }
        ch.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("end", CharsetUtil.UTF_8), add));
        // LOGGER.info(":{},:{}", REQ_NUM, System.nanoTime() -
        // start);
        System.out.printf(":%d,:%d", REQ_NUM, System.nanoTime() - start);
        if (!ch.closeFuture().await(5000)) {
            System.err.println("QOTM request timed out.");
        }
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.whirvis.jraknet.client.peer.PeerFactory.java

License:Open Source License

/**
 * Further assembles the peer creation by handling the specified packet.
 * /*from w  w  w  .  jav  a  2  s  .  co  m*/
 * @param packet
 *            the packet to handle.
 * @return the created peer, <code>null</code> if the peer is not yet
 *         finished assembling.
 * @throws NullPointerException
 *             if the <code>packet</code> is <code>null</code>.
 * @throws IllegalStateException
 *             if the peer is not currently being assembled or if the peer
 *             has already been assembled.
 */
public RakNetServerPeer assemble(RakNetPacket packet) throws NullPointerException, IllegalStateException {
    if (packet == null) {
        throw new NullPointerException("Packet cannot be null");
    } else if (factoryState <= STATE_IDLE) {
        throw new IllegalStateException("Peer is not currently being assembled");
    } else if (factoryState >= STATE_PEER_ASSEMBLED) {
        throw new IllegalStateException("Peer has already been assembled");
    } else {
        try {
            if (packet.getId() == ID_OPEN_CONNECTION_REPLY_1
                    && factoryState == STATE_FIRST_CONNECTION_REQUEST) {
                OpenConnectionResponseOne connectionResponseOne = new OpenConnectionResponseOne(packet);
                connectionResponseOne.decode();
                if (connectionResponseOne.magic == false) {
                    throw new InvalidMagicException(client);
                } else if (connectionResponseOne.maximumTransferUnit < RakNet.MINIMUM_MTU_SIZE) {
                    throw new InvalidMaximumTransferUnitException(client,
                            connectionResponseOne.maximumTransferUnit);
                }

                /*
                 * If the maximum transfer unit of the server is smaller
                 * than that of the client, then use that one. Otherwise,
                 * use the highest valid maximum transfer unit of the
                 * client.
                 */
                this.maximumTransferUnit = connectionResponseOne.maximumTransferUnit < maximumMaximumTransferUnit
                        ? connectionResponseOne.maximumTransferUnit
                        : maximumMaximumTransferUnit;
                this.serverGuid = connectionResponseOne.serverGuid;
                this.factoryState = STATE_SECOND_CONNECTION_REQUEST;
                log.debug("Applied maximum transfer unit " + maximumTransferUnit + " and globally unique ID "
                        + serverGuid + " from " + getName(packet.getId()) + " packet");
            } else if (packet.getId() == ID_OPEN_CONNECTION_REPLY_2
                    && factoryState == STATE_SECOND_CONNECTION_REQUEST) {
                OpenConnectionResponseTwo connectionResponseTwo = new OpenConnectionResponseTwo(packet);
                connectionResponseTwo.decode();
                if (connectionResponseTwo.failed()) {
                    throw new PacketBufferException(connectionResponseTwo);
                } else if (connectionResponseTwo.magic == false) {
                    throw new InvalidMagicException(client);
                } else if (connectionResponseTwo.serverGuid != serverGuid) {
                    throw new InconsistentGuidException(client);
                } else if (connectionResponseTwo.maximumTransferUnit > maximumMaximumTransferUnit
                        || connectionResponseTwo.maximumTransferUnit < RakNet.MINIMUM_MTU_SIZE) {
                    throw new InvalidMaximumTransferUnitException(client, maximumTransferUnit);
                }

                // Update maximum transfer unit if needed
                if (connectionResponseTwo.maximumTransferUnit < maximumTransferUnit) {
                    this.maximumTransferUnit = connectionResponseTwo.maximumTransferUnit;
                    log.warn("Server responded with lower maximum transfer unit than agreed upon earlier");
                } else if (connectionResponseTwo.maximumTransferUnit > maximumMaximumTransferUnit) {
                    this.maximumTransferUnit = connectionResponseTwo.maximumTransferUnit;
                    log.warn("Server responded with higher maximum transfer unit than agreed upon earlier");
                }

                bootstrap.option(ChannelOption.SO_SNDBUF, maximumTransferUnit).option(ChannelOption.SO_RCVBUF,
                        maximumTransferUnit);

                // Create peer
                this.connectionType = connectionResponseTwo.connectionType;
                this.factoryState = STATE_PEER_ASSEMBLED;
                client.callEvent(listener -> listener.onConnect(client, address, connectionType));
                log.debug("Created server peer using globally unique ID "
                        + Long.toHexString(serverGuid).toUpperCase()
                        + " and maximum transfer unit with size of " + maximumTransferUnit + " bytes ("
                        + (maximumTransferUnit * 8) + " bits) for server address " + address);
                return new RakNetServerPeer(client, address, serverGuid, maximumTransferUnit, connectionType,
                        channel);
            } else if (packet.getId() == ID_ALREADY_CONNECTED) {
                throw new AlreadyConnectedException(client, address);
            } else if (packet.getId() == ID_NO_FREE_INCOMING_CONNECTIONS) {
                throw new NoFreeIncomingConnectionsException(client, address);
            } else if (packet.getId() == ID_CONNECTION_BANNED) {
                ConnectionBanned connectionBanned = new ConnectionBanned(packet);
                connectionBanned.decode();
                if (connectionBanned.magic != true) {
                    throw new InvalidMagicException(client);
                } else if (connectionBanned.serverGuid == serverGuid) {
                    throw new ConnectionBannedException(client, address);
                }
            } else if (packet.getId() == ID_INCOMPATIBLE_PROTOCOL_VERSION) {
                IncompatibleProtocolVersion incompatibleProtocol = new IncompatibleProtocolVersion(packet);
                incompatibleProtocol.decode();
                if (incompatibleProtocol.serverGuid == serverGuid) {
                    throw new IncompatibleProtocolException(client, address, client.getProtocolVersion(),
                            incompatibleProtocol.networkProtocol);
                }
            }
        } catch (PeerFactoryException | PacketBufferException e) {
            this.exceptionCaught(e);
        }
    }
    return null;
}

From source file:com.whirvis.jraknet.RakNet.java

License:Open Source License

/**
 * Sends a packet to the specified address.
 * /*from   w ww. ja  v  a 2s .  c  om*/
 * @param address
 *            the address to send the packet to.
 * @param packet
 *            the packet to send.
 * @param timeout
 *            how long to wait until resending the packet.
 * @param retries
 *            how many times the packet will be sent before giving up.
 * @return the packet received in response, <code>null</code> if no response
 *         was received or the thread was interrupted.
 * @throws NullPointerException
 *             if the <code>address</code>, IP address of the
 *             <code>address</code>, or <code>packet</code> are
 *             <code>null</code>.
 * @throws IllegalArgumentException
 *             if the <code>timeout</code> or <code>retries</code> are less
 *             than or equal to <code>0</code>.
 */
private static RakNetPacket createBootstrapAndSend(InetSocketAddress address, Packet packet, long timeout,
        int retries) throws NullPointerException, IllegalArgumentException {
    if (address == null) {
        throw new NullPointerException("Address cannot be null");
    } else if (address.getAddress() == null) {
        throw new NullPointerException("IP address cannot be null");
    } else if (packet == null) {
        throw new NullPointerException("Packet cannot be null");
    } else if (timeout <= 0) {
        throw new IllegalArgumentException("Timeout must be greater than 0");
    } else if (retries <= 0) {
        throw new IllegalArgumentException("Retriest must be greater than 0");
    }

    // Prepare bootstrap
    RakNetPacket received = null;
    EventLoopGroup group = new NioEventLoopGroup();
    int maximumTransferUnit = getMaximumTransferUnit();
    if (maximumTransferUnit < MINIMUM_MTU_SIZE) {
        return null;
    }
    try {
        // Create bootstrap
        Bootstrap bootstrap = new Bootstrap();
        BootstrapHandler handler = new BootstrapHandler();
        bootstrap.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
                .option(ChannelOption.SO_RCVBUF, maximumTransferUnit)
                .option(ChannelOption.SO_SNDBUF, maximumTransferUnit).handler(handler);
        Channel channel = bootstrap.bind(0).sync().channel();

        // Wait for response
        while (retries > 0 && received == null && !Thread.currentThread().isInterrupted()) {
            long sendTime = System.currentTimeMillis();
            channel.writeAndFlush(new DatagramPacket(packet.buffer(), address));
            while (System.currentTimeMillis() - sendTime < timeout && handler.packet == null)
                ; // Wait for either a timeout or a response
            received = handler.packet;
            retries--;
        }
    } catch (InterruptedException e) {
        return null;
    }
    group.shutdownGracefully();
    return received;
}

From source file:com.whirvis.jraknet.server.RakNetServer.java

License:Open Source License

/**
 * Starts the server./*from  w w  w .ja  va 2s.  c  o m*/
 * 
 * @throws IllegalStateException
 *             if the server is already running.
 * @throws RakNetException
 *             if an error occurs during startup.
 */
public void start() throws IllegalStateException, RakNetException {
    if (running == true) {
        throw new IllegalStateException("Server is already running");
    } else if (listeners.isEmpty()) {
        log.warn("Server has no listeners");
    }

    try {
        this.bootstrap = new Bootstrap();
        this.group = new NioEventLoopGroup();
        this.handler = new RakNetServerHandler(this);
        bootstrap.handler(handler);

        // Create bootstrap and bind channel
        bootstrap.channel(NioDatagramChannel.class).group(group);
        bootstrap.option(ChannelOption.SO_BROADCAST, true).option(ChannelOption.SO_REUSEADDR, false)
                .option(ChannelOption.SO_SNDBUF, maximumTransferUnit)
                .option(ChannelOption.SO_RCVBUF, maximumTransferUnit);
        this.channel = (bindingAddress != null ? bootstrap.bind(bindingAddress) : bootstrap.bind(0)).sync()
                .channel();
        this.bindAddress = (InetSocketAddress) channel.localAddress();
        this.running = true;
        log.debug("Created and bound bootstrap");

        // Create and start peer update thread
        RakNetServer server = this;
        this.peerThread = new Thread(
                RakNetServer.class.getSimpleName() + "-Peer-Thread-" + Long.toHexString(guid).toUpperCase()) {

            @Override
            public void run() {
                HashMap<RakNetClientPeer, Throwable> disconnected = new HashMap<RakNetClientPeer, Throwable>();
                while (server.running == true && !this.isInterrupted()) {
                    try {
                        Thread.sleep(0, 1); // Lower CPU usage
                    } catch (InterruptedException e) {
                        this.interrupt(); // Interrupted during sleep
                        continue;
                    }
                    for (RakNetClientPeer peer : clients.values()) {
                        if (!peer.isDisconnected()) {
                            try {
                                peer.update();
                                if (peer.getPacketsReceivedThisSecond() >= RakNet.getMaxPacketsPerSecond()) {
                                    server.blockAddress(peer.getInetAddress(), "Too many packets",
                                            RakNet.MAX_PACKETS_PER_SECOND_BLOCK);
                                }
                            } catch (Throwable throwable) {
                                server.callEvent(listener -> listener.onPeerException(server, peer, throwable));
                                disconnected.put(peer, throwable);
                            }
                        }
                    }

                    /*
                     * Disconnect peers.
                     * 
                     * This must be done here as simply removing a client
                     * from the clients map would be an incorrect way of
                     * disconnecting a client. This means that calling the
                     * disconnect() method is required. However, calling it
                     * while in the loop would cause a
                     * ConcurrentModifactionException. To get around this,
                     * the clients that need to be disconnected are properly
                     * disconnected after the loop is finished. This is done
                     * simply by having them and their disconnect reason be
                     * put in a disconnection map.
                     */
                    if (disconnected.size() > 0) {
                        for (RakNetClientPeer peer : disconnected.keySet()) {
                            server.disconnect(peer, disconnected.get(peer));
                        }
                        disconnected.clear();
                    }
                }
            }

        };
        peerThread.start();
        log.debug("Created and started peer update thread");
        this.callEvent(listener -> listener.onStart(this));
    } catch (InterruptedException e) {
        this.running = false;
        throw new RakNetException(e);
    }
    log.info("Started server");
}

From source file:com.wolfbe.configcenter.remoting.netty.NettyRemotingClient.java

License:Apache License

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

                private AtomicInteger threadIndex = new AtomicInteger(0);

                @Override// w w w .  j a v  a 2 s .  co  m
                public Thread newThread(Runnable r) {
                    return new Thread(r, "NettyClientWorkerThread_" + this.threadIndex.incrementAndGet());
                }
            });

    Bootstrap handler = this.bootstrap.group(this.eventLoopGroupWorker).channel(NioSocketChannel.class)//
            //
            .option(ChannelOption.TCP_NODELAY, true)
            //
            .option(ChannelOption.SO_KEEPALIVE, false)
            //
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, nettyClientConfig.getConnectTimeoutMillis())
            //
            .option(ChannelOption.SO_SNDBUF, nettyClientConfig.getClientSocketSndBufSize())
            //
            .option(ChannelOption.SO_RCVBUF, nettyClientConfig.getClientSocketRcvBufSize())
            //
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(//
                            defaultEventExecutorGroup, //
                            new NettyEncoder(), //
                            new NettyDecoder(), //
                            new IdleStateHandler(0, 0, nettyClientConfig.getClientChannelMaxIdleTimeSeconds()), //
                            new NettyConnetManageHandler(), //
                            new NettyClientHandler());
                }
            });

    this.timer.scheduleAtFixedRate(new TimerTask() {

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

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

From source file:com.wolfbe.configcenter.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//  w w w  . ja  v  a  2s .  com
                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 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();
    }

    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.ztesoft.zsmart.zmq.remoting.netty.NettyRemotingServer.java

License:Apache License

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

                private AtomicInteger threadIndex = new AtomicInteger(0);

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

    ServerBootstrap childHandler = //
            this.serverBootstrap.group(this.eventLoopGroupBoss, this.eventLoopGroupWorker)
                    .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 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:darks.grid.network.GridMessageClient.java

License:Apache License

@Override
public boolean initialize() {
    super.initialize();
    try {/*from  w ww  . j av a 2  s  .  co  m*/
        log.info("Initialize message client.");
        NetworkConfig config = GridRuntime.config().getNetworkConfig();
        int workerNum = config.getClientWorkerThreadNumber();
        workerGroup = new NioEventLoopGroup(workerNum, ThreadUtils.getThreadFactory());
        bootstrap = new Bootstrap();
        bootstrap.group(workerGroup).channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, config.isTcpNodelay())
                .option(ChannelOption.SO_KEEPALIVE, config.isTcpKeepAlive())
                .option(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(true))
                //                   .option(ChannelOption.SO_TIMEOUT, config.getRecvTimeout())
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getConnectTimeout())
                .option(ChannelOption.SO_SNDBUF, config.getTcpSendBufferSize())
                .option(ChannelOption.SO_RCVBUF, config.getTcpRecvBufferSize());
        bootstrap.handler(newChannelHandler());
        return true;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        return false;
    }
}

From source file:darks.grid.network.GridMessageServer.java

License:Apache License

@Override
public boolean initialize() {
    try {/*  ww  w. j  a  va2s  .c  o m*/
        NetworkConfig config = GridRuntime.config().getNetworkConfig();
        int bossNum = Runtime.getRuntime().availableProcessors() * config.getServerBossThreadDelta();
        int workerNum = config.getServerWorkerThreadNumber();
        bossGroup = new NioEventLoopGroup(bossNum);
        workerGroup = new NioEventLoopGroup(workerNum);
        super.initialize();
        bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, config.isTcpNodelay())
                .option(ChannelOption.SO_KEEPALIVE, config.isTcpKeepAlive())
                .option(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(true))
                //            .option(ChannelOption.SO_TIMEOUT, config.getRecvTimeout())
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getConnectTimeout())
                .option(ChannelOption.SO_REUSEADDR, config.isTcpReuseAddr())
                //            .option(ChannelOption.SO_BACKLOG, config.getTcpBacklog())
                .option(ChannelOption.SO_SNDBUF, config.getTcpSendBufferSize())
                .option(ChannelOption.SO_RCVBUF, config.getTcpRecvBufferSize())
                .childOption(ChannelOption.TCP_NODELAY, config.isTcpNodelay())
                .childOption(ChannelOption.SO_KEEPALIVE, config.isTcpKeepAlive())
                .childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(true))
                .childOption(ChannelOption.SO_TIMEOUT, config.getRecvTimeout())
                .childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getConnectTimeout())
                .childOption(ChannelOption.SO_REUSEADDR, config.isTcpReuseAddr())
                .childOption(ChannelOption.SO_BACKLOG, config.getTcpBacklog())
                .childOption(ChannelOption.SO_SNDBUF, config.getTcpSendBufferSize())
                .childOption(ChannelOption.SO_RCVBUF, config.getTcpRecvBufferSize());
        bootstrap.childHandler(newChannelHandler());
        return true;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        return false;
    }
}