Example usage for io.netty.channel ChannelOption TCP_NODELAY

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

Introduction

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

Prototype

ChannelOption TCP_NODELAY

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

Click Source Link

Usage

From source file:org.kualigan.maven.plugins.AbstractStartRedisMojo.java

License:Apache License

/**
 * Start the redis server//from  ww  w  .  j a  v a  2 s .c  o  m
 *
 * @param isForked is a {@link Boolean} determing whether to fork the redis server or not.
 */
public void start(final Boolean isForked) throws InterruptedException {
    // Only execute the command handler in a single thread
    final RedisCommandHandler commandHandler = new RedisCommandHandler(new SimpleRedisServer());

    // Configure the server.
    final ServerBootstrap b = new ServerBootstrap();
    final DefaultEventExecutorGroup group = new DefaultEventExecutorGroup(1);
    getPluginContext().put(REDIS_GROUP_CONTEXT_PROPERTY_NAME, group);

    try {
        b.group(new NioEventLoopGroup(), new NioEventLoopGroup()).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).localAddress(getPort())
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        final ChannelPipeline p = ch.pipeline();
                        p.addLast(new RedisCommandDecoder());
                        p.addLast(new RedisReplyEncoder());
                        p.addLast(group, commandHandler);
                    }
                });

        final StringBuffer message = new StringBuffer();

        // Start the server.
        if (isForked) {
            message.append("Forking Redis");
        } else {
            message.append("Starting Redis");
        }

        message.append("(port=").append(getPort()).append(") server...");
        getLog().info(message.toString());

        final ChannelFuture f = b.bind();

        // Wait until the server socket is closed.
        if (!isForked) {
            f.sync();
            f.channel().closeFuture().sync();
        }
    } finally {
        // Shut down all event loops to terminate all threads.
        group.shutdownGracefully();
    }
}

From source file:org.lanternpowered.pingy.Pingy.java

License:MIT License

/**
 * Starts the pingy server.//from ww  w  .  j  a va 2s.  c  o  m
 *
 * @throws IOException
 */
public void start() throws IOException {
    boolean epoll = false;

    if (this.properties.isUseEpollWhenAvailable()) {
        if (Epoll.isAvailable()) {
            debugInfo("Epoll is available");
            epoll = true;
        } else {
            debugWarn(
                    "Epoll is unavailable (The following exception is only used to print the cause why it's unavailable, "
                            + "it won't affect the functionality.)");
            //noinspection ThrowableResultOfMethodCallIgnored
            debug(() -> Epoll.unavailabilityCause().printStackTrace());
        }
    }

    final ServerBootstrap bootstrap = new ServerBootstrap();
    final EventLoopGroup group = epoll ? new EpollEventLoopGroup() : new NioEventLoopGroup();

    final ChannelFuture future = bootstrap.group(group)
            .channel(epoll ? EpollServerSocketChannel.class : NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ReadTimeoutHandler(20))
                            .addLast(new PingyLegacyHandler(properties)).addLast(new PingyFramingHandler())
                            .addLast(new PingyHandler(properties));
                }
            }).childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true)
            .bind(getBindAddress(this.properties.getIp(), this.properties.getPort()));
    final Channel channel = future.awaitUninterruptibly().channel();
    if (!channel.isActive()) {
        final Throwable cause = future.cause();
        if (cause instanceof BindException) {
            throw (BindException) cause;
        }
        throw new RuntimeException("Failed to bind to address", cause);
    }
    info("Successfully bound to: " + channel.localAddress());
}

From source file:org.lanternpowered.server.network.NetworkManager.java

License:MIT License

@Override
protected ChannelFuture init0(SocketAddress address, boolean epoll) {
    this.bootstrap = new ServerBootstrap();
    // Take advantage of the fast thread local threads,
    // this is also provided by the default thread factory
    final ThreadFactory threadFactory = ThreadHelper
            .newFastThreadLocalThreadFactory(() -> "netty-" + threadCounter.getAndIncrement());
    this.bossGroup = createEventLoopGroup(epoll, threadFactory);
    this.workerGroup = createEventLoopGroup(epoll, threadFactory);
    this.socketAddress = address;
    return this.bootstrap.group(this.bossGroup, this.workerGroup).channel(getServerSocketChannelClass(epoll))
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override/*from  w w w .  java2s  . co  m*/
                protected void initChannel(SocketChannel ch) throws Exception {
                    final ChannelPipeline pipeline = ch.pipeline();
                    final NetworkSession networkSession = new NetworkSession(ch, server, NetworkManager.this);
                    final CodecContext codecContext = new SimpleCodecContext(
                            new LanternByteBufferAllocator(ch.alloc()), ch, networkSession);
                    pipeline.addLast(new ReadTimeoutHandler(NetworkSession.READ_TIMEOUT_SECONDS))
                            .addLast(NetworkSession.LEGACY_PING, new LegacyProtocolHandler(networkSession))
                            .addLast(NetworkSession.ENCRYPTION, NoopHandler.INSTANCE)
                            .addLast(NetworkSession.FRAMING, new MessageFramingHandler())
                            .addLast(NetworkSession.COMPRESSION, NoopHandler.INSTANCE)
                            .addLast(NetworkSession.CODECS, new MessageCodecHandler(codecContext))
                            .addLast(NetworkSession.PROCESSOR, new MessageProcessorHandler(codecContext))
                            .addLast(NetworkSession.HANDLER, networkSession);
                }
            }).childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true)
            .bind(address);
}

From source file:org.legacy.network.Network.java

License:Open Source License

public void bindNetwork() {
    bootstrap = new ServerBootstrap();
    bootstrap.group(new NioEventLoopGroup(), new NioEventLoopGroup());
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.option(ChannelOption.SO_BACKLOG, 100);
    bootstrap.childOption(ChannelOption.TCP_NODELAY, true);
    bootstrap.childHandler(new Pipeline());
    try {/*from  www  . ja  va2s  .  co  m*/
        bootstrap.localAddress(43594).bind().sync();
    } catch (InterruptedException exception) {
        LegacyLogger.fireErrorMessage(this, "Error in binding the network", exception);
    }
}

From source file:org.maodian.flyingcat.xmpp.XmppServer.java

License:Apache License

private void run(ApplicationContext beanFactory) throws InterruptedException {
    ServerBootstrap b = new ServerBootstrap();
    try {/*from   ww  w  .  java  2  s  .  c o  m*/
        b.group(new NioEventLoopGroup(), new NioEventLoopGroup()).channel(NioServerSocketChannel.class)
                .localAddress(port).childHandler(new XmppServerInitializer(beanFactory))
                .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true);

        b.bind().sync().channel().closeFuture().sync();
    } finally {
        b.shutdown();
    }
}

From source file:org.marketcetera.client.rpc.RpcClientImpl.java

@Override
protected void connectWebServices() throws I18NException, RemoteException {
    SLF4JLoggerProxy.debug(this, "Connecting to RPC server at {}:{}", mParameters.getHostname(),
            mParameters.getPort());/*from   ww w .  ja  va  2 s .co m*/
    PeerInfo server = new PeerInfo(mParameters.getHostname(), mParameters.getPort());
    DuplexTcpClientPipelineFactory clientFactory = new DuplexTcpClientPipelineFactory();
    executor = new ThreadPoolCallExecutor(1, 10);
    clientFactory.setRpcServerCallExecutor(executor);
    clientFactory.setConnectResponseTimeoutMillis(10000);
    clientFactory.setCompression(true);
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(new NioEventLoopGroup());
    bootstrap.handler(clientFactory);
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
    bootstrap.option(ChannelOption.SO_SNDBUF, 1048576);
    bootstrap.option(ChannelOption.SO_RCVBUF, 1048576);
    try {
        channel = clientFactory.peerWith(server, bootstrap);
        clientService = RpcClientService.newBlockingStub(channel);
        controller = channel.newRpcController();
        java.util.Locale currentLocale = java.util.Locale.getDefault();
        LoginRequest loginRequest = LoginRequest.newBuilder().setAppId(ClientVersion.APP_ID.getValue())
                .setVersionId(ClientVersion.APP_ID_VERSION.getVersionInfo())
                .setClientId(NodeId.generate().getValue())
                .setLocale(Locale.newBuilder()
                        .setCountry(currentLocale.getCountry() == null ? "" : currentLocale.getCountry())
                        .setLanguage(currentLocale.getLanguage() == null ? "" : currentLocale.getLanguage())
                        .setVariant(currentLocale.getVariant() == null ? "" : currentLocale.getVariant())
                        .build())
                .setUsername(mParameters.getUsername()).setPassword(new String(mParameters.getPassword()))
                .build();
        LoginResponse loginResponse = clientService.login(controller, loginRequest);
        sessionId = new SessionId(loginResponse.getSessionId());
    } catch (IOException | ServiceException e) {
        throw new RemoteException(e);
    }
}

From source file:org.marketcetera.marketdata.core.rpc.MarketDataRpcClient.java

/**
 * Starts the remote service./*from   w  ww. j a  v  a  2s .c  om*/
 *
 * @throws IOException if an error occurs starting the service
 * @throws ServiceException if an error occurs starting the service
 */
private void startService() throws IOException, ServiceException {
    try (CloseableLock startLock = CloseableLock.create(serviceLock.writeLock())) {
        startLock.lock();
        SLF4JLoggerProxy.debug(this, "Connecting to RPC server at {}:{}", //$NON-NLS-1$
                hostname, port);
        PeerInfo server = new PeerInfo(hostname, port);
        DuplexTcpClientPipelineFactory clientFactory = new DuplexTcpClientPipelineFactory();
        executor = new ThreadPoolCallExecutor(1, 10);
        clientFactory.setRpcServerCallExecutor(executor);
        clientFactory.setConnectResponseTimeoutMillis(10000);
        clientFactory.setCompression(true);
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(new NioEventLoopGroup());
        bootstrap.handler(clientFactory);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.TCP_NODELAY, true);
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
        bootstrap.option(ChannelOption.SO_SNDBUF, 1048576);
        bootstrap.option(ChannelOption.SO_RCVBUF, 1048576);
        channel = clientFactory.peerWith(server, bootstrap);
        clientService = RpcMarketDataService.newBlockingStub(channel);
        controller = channel.newRpcController();
        java.util.Locale currentLocale = java.util.Locale.getDefault();
        LoginRequest loginRequest = LoginRequest.newBuilder().setAppId(APP_ID.getValue())
                .setVersionId(APP_ID_VERSION.getVersionInfo()).setClientId(NodeId.generate().getValue())
                .setLocale(Locale.newBuilder()
                        .setCountry(currentLocale.getCountry() == null ? "" : currentLocale.getCountry()) //$NON-NLS-1$
                        .setLanguage(currentLocale.getLanguage() == null ? "" : currentLocale.getLanguage()) //$NON-NLS-1$
                        .setVariant(currentLocale.getVariant() == null ? "" : currentLocale.getVariant()) //$NON-NLS-1$
                        .build()).setUsername(username).setPassword(new String(password)).build();
        LoginResponse loginResponse = clientService.login(controller, loginRequest);
        sessionId = new SessionId(loginResponse.getSessionId());
        setServerStatus(true);
    }
}

From source file:org.marketcetera.saclient.rpc.RpcSAClientImpl.java

/**
 * Starts the remote service./*from  w w  w . j av a2s. c  o  m*/
 *
 * @throws IOException if an error occurs starting the service
 * @throws ServiceException if an error occurs starting the service
 */
private void startService() throws IOException, ServiceException {
    try (CloseableLock startLock = CloseableLock.create(serviceLock.writeLock())) {
        startLock.lock();
        SLF4JLoggerProxy.debug(this, "Connecting to RPC server at {}:{}", //$NON-NLS-1$
                parameters.getHostname(), parameters.getPort());
        PeerInfo server = new PeerInfo(parameters.getHostname(), parameters.getPort());
        DuplexTcpClientPipelineFactory clientFactory = new DuplexTcpClientPipelineFactory();
        executor = new ThreadPoolCallExecutor(1, 10);
        clientFactory.setRpcServerCallExecutor(executor);
        clientFactory.setConnectResponseTimeoutMillis(10000);
        clientFactory.setCompression(true);
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(new NioEventLoopGroup());
        bootstrap.handler(clientFactory);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.TCP_NODELAY, true);
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
        bootstrap.option(ChannelOption.SO_SNDBUF, 1048576);
        bootstrap.option(ChannelOption.SO_RCVBUF, 1048576);
        channel = clientFactory.peerWith(server, bootstrap);
        clientService = RpcSAClientService.newBlockingStub(channel);
        controller = channel.newRpcController();
        java.util.Locale currentLocale = java.util.Locale.getDefault();
        LoginRequest loginRequest = LoginRequest.newBuilder().setAppId(SAClientVersion.APP_ID.getValue())
                .setVersionId(SAClientVersion.APP_ID_VERSION.getVersionInfo())
                .setClientId(NodeId.generate().getValue())
                .setLocale(Locale.newBuilder()
                        .setCountry(currentLocale.getCountry() == null ? "" : currentLocale.getCountry()) //$NON-NLS-1$
                        .setLanguage(currentLocale.getLanguage() == null ? "" : currentLocale.getLanguage()) //$NON-NLS-1$
                        .setVariant(currentLocale.getVariant() == null ? "" : currentLocale.getVariant()) //$NON-NLS-1$
                        .build()).setUsername(parameters.getUsername()).setPassword(new String(parameters.getPassword()))
                .build();
        LoginResponse loginResponse = clientService.login(controller, loginRequest);
        sessionId = new SessionId(loginResponse.getSessionId());
        connectionStatusChanged(isRunning(), true);
    }
}

From source file:org.marketcetera.util.rpc.RpcServer.java

@Override
@PostConstruct//from w w  w  . j a v a 2  s  . c o  m
public synchronized void start() {
    Validate.notNull(hostname);
    Validate.isTrue(port > 0 && port < 65536);
    Validate.notNull(sessionManager);
    Validate.notNull(authenticator);
    Validate.isTrue(threadPoolCore > 0);
    Validate.isTrue(threadPoolMax > 0);
    Validate.isTrue(threadPoolMax >= threadPoolCore);
    Validate.isTrue(sendBufferSize > 0);
    Validate.isTrue(receiveBufferSize > 0);
    Validate.notEmpty(serviceSpecs);
    Messages.SERVER_STARTING.info(this, hostname, port);
    if (isRunning()) {
        stop();
    }
    try {
        reportContext = JAXBContext.newInstance(
                contextClassProvider == null ? new Class<?>[0] : contextClassProvider.getContextClasses());
        marshaller = reportContext.createMarshaller();
        unmarshaller = reportContext.createUnmarshaller();
    } catch (JAXBException e) {
        SLF4JLoggerProxy.error(this, e);
        throw new RuntimeException(e);
    }
    PeerInfo serverInfo = new PeerInfo(getRpcHostname(), getRpcPort());
    executor = new ThreadPoolCallExecutor(threadPoolCore, threadPoolMax);
    DuplexTcpServerPipelineFactory serverFactory = new DuplexTcpServerPipelineFactory(serverInfo);
    serverFactory.setRpcServerCallExecutor(executor);
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(
            new NioEventLoopGroup(0, new RenamingThreadFactoryProxy("boss", Executors.defaultThreadFactory())),
            new NioEventLoopGroup(0,
                    new RenamingThreadFactoryProxy("worker", Executors.defaultThreadFactory())));
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.childHandler(serverFactory);
    bootstrap.localAddress(serverInfo.getPort());
    bootstrap.option(ChannelOption.SO_SNDBUF, sendBufferSize);
    bootstrap.option(ChannelOption.SO_RCVBUF, receiveBufferSize);
    bootstrap.childOption(ChannelOption.SO_RCVBUF, receiveBufferSize);
    bootstrap.childOption(ChannelOption.SO_SNDBUF, sendBufferSize);
    bootstrap.option(ChannelOption.TCP_NODELAY, noDelay);
    for (RpcServiceSpec<SessionClazz> serviceSpec : serviceSpecs) {
        serviceSpec.setRpcServerServices(this);
        BlockingService activeService = serviceSpec.generateService();
        serverFactory.getRpcServiceRegistry().registerService(activeService);
        Messages.SERVICE_STARTING.info(this, serviceSpec.getDescription());
    }
    channelToken = bootstrap.bind();
    while (!channelToken.isDone()) {
        try {
            Thread.sleep(250);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
    // TODO throw exception?
    running.set(channelToken.isSuccess());
    //RpcClientConnectionRegistry clientRegistry = new RpcClientConnectionRegistry();
    //serverFactory.registerConnectionEventListener(clientRegistry);
}

From source file:org.mobicents.protocols.sctp.netty.NettyAssociationImpl.java

License:Open Source License

protected void connect() {
    if (!this.started || this.up) {
        // return if not started or already up
        return;/*from  w w w  . java 2s.co  m*/
    }

    if (logger.isDebugEnabled()) {
        logger.debug(String.format("Initiating connection started: Association=%s", this));
    }

    Bootstrap b;
    InetSocketAddress localAddress;
    try {
        EventLoopGroup group = this.management.getBossGroup();
        b = new Bootstrap();

        b.group(group);
        if (this.ipChannelType == IpChannelType.SCTP) {
            b.channel(NioSctpChannel.class);

            // applying of stack level SCTP options
            this.applySctpOptions(b);

            b.handler(new NettySctpClientChannelInitializer(this));
        } else {
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.TCP_NODELAY, true);
            b.handler(new NettyTcpClientChannelInitializer(this));
        }

        localAddress = new InetSocketAddress(this.hostAddress, this.hostPort);
    } catch (Exception e) {
        logger.error(String.format("Exception while creating connection for Association=%s", this.getName()),
                e);
        this.scheduleConnect();
        return;
    }

    // Bind the client channel.
    try {
        ChannelFuture bindFuture = b.bind(localAddress).sync();
        Channel channel = bindFuture.channel();

        if (this.ipChannelType == IpChannelType.SCTP) {
            // Get the underlying sctp channel
            SctpChannel sctpChannel = (SctpChannel) channel;

            // Bind the secondary address.
            // Please note that, bindAddress in the client channel should be done before connecting if you have not
            // enable Dynamic Address Configuration. See net.sctp.addip_enable kernel param
            if (this.extraHostAddresses != null) {
                for (int count = 0; count < this.extraHostAddresses.length; count++) {
                    String localSecondaryAddress = this.extraHostAddresses[count];
                    InetAddress localSecondaryInetAddress = InetAddress.getByName(localSecondaryAddress);

                    sctpChannel.bindAddress(localSecondaryInetAddress).sync();
                }
            }
        }

        InetSocketAddress remoteAddress = new InetSocketAddress(this.peerAddress, this.peerPort);

        // Finish connect
        bindFuture.channel().connect(remoteAddress);
        if (logger.isDebugEnabled()) {
            logger.debug(String.format("Initiating connection scheduled: Association=%s remoteAddress=%s", this,
                    remoteAddress));
        }
    } catch (Exception e) {
        logger.error(String.format("Exception while finishing connection for Association=%s", this.getName()),
                e);
    }
}