Example usage for io.netty.channel ChannelOption SO_KEEPALIVE

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

Introduction

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

Prototype

ChannelOption SO_KEEPALIVE

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

Click Source Link

Usage

From source file:org.opendaylight.protocol.bmp.impl.app.BmpMonitorImplTest.java

License:Open Source License

private Channel connectTestClient(final String routerIp, final BmpMessageRegistry msgRegistry)
        throws InterruptedException {
    final BmpHandlerFactory hf = new BmpHandlerFactory(msgRegistry);
    final Bootstrap b = new Bootstrap();
    final EventLoopGroup workerGroup;
    if (Epoll.isAvailable()) {
        b.channel(EpollSocketChannel.class);
        workerGroup = new EpollEventLoopGroup();
    } else {//from   w w w .j a  v  a  2s  . com
        b.channel(NioSocketChannel.class);
        workerGroup = new NioEventLoopGroup();
    }
    b.group(workerGroup);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(final SocketChannel ch) throws Exception {
            ch.pipeline().addLast(hf.getDecoders());
            ch.pipeline().addLast(hf.getEncoders());
        }
    });
    b.localAddress(new InetSocketAddress(routerIp, 0));
    b.option(ChannelOption.SO_REUSEADDR, true);
    final ChannelFuture future = b.connect(new InetSocketAddress(MONITOR_LOCAL_ADDRESS, MONITOR_LOCAL_PORT))
            .sync();
    waitFutureSuccess(future);
    return future.channel();
}

From source file:org.opendaylight.protocol.bmp.impl.BmpDispatcherImpl.java

License:Open Source License

@Override
public ChannelFuture createClient(final InetSocketAddress address, final BmpSessionListenerFactory slf,
        final Optional<KeyMapping> keys) {

    final Bootstrap b = new Bootstrap();

    Preconditions.checkNotNull(address);

    if (Epoll.isAvailable()) {
        b.channel(EpollSocketChannel.class);
    } else {// w  w w . ja v a  2s  . co m
        b.channel(NioSocketChannel.class);
    }
    if (keys.isPresent()) {
        if (Epoll.isAvailable()) {
            b.option(EpollChannelOption.TCP_MD5SIG, keys.get());
        } else {
            throw new UnsupportedOperationException(Epoll.unavailabilityCause().getCause());
        }
    }
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT);
    b.group(this.workerGroup);

    b.handler(new ChannelInitializer<AbstractChannel>() {
        @Override
        protected void initChannel(final AbstractChannel ch) throws Exception {
            ch.pipeline().addLast(BmpDispatcherImpl.this.hf.getDecoders());
            ch.pipeline().addLast(BmpDispatcherImpl.this.sessionFactory.getSession(ch, slf));
        }
    });

    b.remoteAddress(address);
    final ChannelFuture channelPromise = b.connect();
    channelPromise.addListener(new BmpDispatcherImpl.BootstrapListener(b, address));
    return channelPromise;
}

From source file:org.opendaylight.protocol.bmp.mock.BmpMockDispatcher.java

License:Open Source License

private Bootstrap createClientInstance(final SocketAddress localAddress) {
    final NioEventLoopGroup workergroup = new NioEventLoopGroup();
    final Bootstrap bootstrap = new Bootstrap();

    bootstrap.channel(NioSocketChannel.class);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT);
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    bootstrap.group(workergroup);// w w  w  .  j  a  va 2 s  . c om

    bootstrap.handler(new ChannelInitializer<NioSocketChannel>() {
        @Override
        protected void initChannel(final NioSocketChannel ch) throws Exception {
            ch.pipeline().addLast(BmpMockDispatcher.this.sessionFactory.getSession(ch, null));
            ch.pipeline().addLast(BmpMockDispatcher.this.hf.getEncoders());
        }
    });
    bootstrap.localAddress(localAddress);
    return bootstrap;
}

From source file:org.opendaylight.protocol.framework.AbstractDispatcher.java

License:Open Source License

/**
 * Creates server. Each server needs factories to pass their instances to client sessions.
 *
 * @param address address to which the server should be bound
 * @param channelClass The {@link Class} which is used to create {@link Channel} instances from.
 * @param initializer instance of PipelineInitializer used to initialize the channel pipeline
 *
 * @return ChannelFuture representing the binding process
 *///from w w w.  j av  a 2 s. co m
protected <CH extends Channel> ChannelFuture createServer(final SocketAddress address,
        final Class<? extends ServerChannel> channelClass,
        final ChannelPipelineInitializer<CH, S> initializer) {
    final ServerBootstrap b = new ServerBootstrap();
    b.childHandler(new ChannelInitializer<CH>() {

        @Override
        protected void initChannel(final CH ch) {
            initializer.initializeChannel(ch, new DefaultPromise<S>(executor));
        }
    });

    b.option(ChannelOption.SO_BACKLOG, 128);
    if (LocalServerChannel.class.equals(channelClass) == false) {
        // makes no sense for LocalServer and produces warning
        b.childOption(ChannelOption.SO_KEEPALIVE, true);
        b.childOption(ChannelOption.TCP_NODELAY, true);
    }
    b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    customizeBootstrap(b);

    if (b.group() == null) {
        b.group(bossGroup, workerGroup);
    }
    try {
        b.channel(channelClass);
    } catch (IllegalStateException e) {
        // FIXME: if this is ok, document why
        LOG.trace("Not overriding channelFactory on bootstrap {}", b, e);
    }

    // Bind and start to accept incoming connections.
    final ChannelFuture f = b.bind(address);
    LOG.debug("Initiated server {} at {}.", f, address);
    return f;
}

From source file:org.opendaylight.protocol.framework.AbstractDispatcher.java

License:Open Source License

/**
 * Creates a client./*from   ww  w.  ja va2  s . c o m*/
 *
 * @param address remote address
 * @param connectStrategy Reconnection strategy to be used when initial connection fails
 *
 * @return Future representing the connection process. Its result represents the combined success of TCP connection
 *         as well as session negotiation.
 */
protected Future<S> createClient(final InetSocketAddress address, final ReconnectStrategy strategy,
        final PipelineInitializer<S> initializer) {
    final Bootstrap b = new Bootstrap();
    final ProtocolSessionPromise<S> p = new ProtocolSessionPromise<>(executor, address, strategy, b);
    b.option(ChannelOption.SO_KEEPALIVE, true).handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(final SocketChannel ch) {
            initializer.initializeChannel(ch, p);
        }
    });

    customizeBootstrap(b);
    setWorkerGroup(b);
    setChannelFactory(b);

    p.connect();
    LOG.debug("Client created.");
    return p;
}

From source file:org.opendaylight.protocol.framework.AbstractDispatcher.java

License:Open Source License

/**
 * Creates a reconnecting client./*from   w  w  w .  ja  va2 s  .c  o m*/
 *
 * @param address remote address
 * @param connectStrategyFactory Factory for creating reconnection strategy for every reconnect attempt
 *
 * @return Future representing the reconnection task. It will report completion based on reestablishStrategy, e.g.
 *         success is never reported, only failure when it runs out of reconnection attempts.
 */
protected Future<Void> createReconnectingClient(final InetSocketAddress address,
        final ReconnectStrategyFactory connectStrategyFactory, final PipelineInitializer<S> initializer) {
    final Bootstrap b = new Bootstrap();

    final ReconnectPromise<S, L> p = new ReconnectPromise<>(GlobalEventExecutor.INSTANCE, this, address,
            connectStrategyFactory, b, initializer);

    b.option(ChannelOption.SO_KEEPALIVE, true);

    customizeBootstrap(b);
    setWorkerGroup(b);
    setChannelFactory(b);

    p.connect();
    return p;
}

From source file:org.opendaylight.protocol.pcep.pcc.mock.protocol.PCCDispatcherImpl.java

License:Open Source License

@Override
public Future<PCEPSession> createClient(@Nonnull final InetSocketAddress remoteAddress,
        @Nonnull final long reconnectTime, @Nonnull final PCEPSessionListenerFactory listenerFactory,
        @Nonnull final PCEPSessionNegotiatorFactory negotiatorFactory, @Nonnull final KeyMapping keys,
        @Nullable final InetSocketAddress localAddress, @Nonnull final BigInteger dbVersion) {
    final Bootstrap b = new Bootstrap();
    b.group(this.workerGroup);
    b.localAddress(localAddress);/*from w w w.  j a v  a2s .com*/
    final Optional<KeyMapping> optionalKey = Optional.fromNullable(keys);
    setChannelFactory(b, optionalKey);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.option(ChannelOption.SO_REUSEADDR, true);
    b.option(ChannelOption.MAX_MESSAGES_PER_READ, 1);
    final long retryTimer = reconnectTime == -1 ? 0 : reconnectTime;
    final PCCReconnectPromise promise = new PCCReconnectPromise(remoteAddress, (int) retryTimer,
            CONNECT_TIMEOUT, b);
    final ChannelInitializer<SocketChannel> channelInitializer = new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(final SocketChannel ch) throws Exception {
            ch.pipeline().addLast(PCCDispatcherImpl.this.factory.getDecoders());
            ch.pipeline().addLast("negotiator", negotiatorFactory.getSessionNegotiator(listenerFactory, ch,
                    promise, new PCCPeerProposal(dbVersion)));
            ch.pipeline().addLast(PCCDispatcherImpl.this.factory.getEncoders());
            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                @Override
                public void channelInactive(final ChannelHandlerContext ctx) throws Exception {
                    if (promise.isCancelled()) {
                        return;
                    }

                    if (!promise.isInitialConnectFinished()) {
                        LOG.debug("Connection to {} was dropped during negotiation, reattempting",
                                remoteAddress);
                        return;
                    }
                    LOG.debug("Reconnecting after connection to {} was dropped", remoteAddress);
                    PCCDispatcherImpl.this.createClient(remoteAddress, reconnectTime, listenerFactory,
                            negotiatorFactory, keys, localAddress, dbVersion);
                }
            });
        }
    };
    b.handler(channelInitializer);
    promise.connect();
    return promise;
}

From source file:org.openremote.agent.protocol.AbstractSocketMessageProcessor.java

License:Open Source License

@Override
protected void configureChannel() {
    super.configureChannel();
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
}

From source file:org.openremote.agent.protocol.io.AbstractIoServer.java

License:Open Source License

/**
 * Configure options to be applied to each client's IO channel
 */
protected void configureClientChannelOptions() {
    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
}

From source file:org.poweredrails.rails.net.NetworkManager.java

License:MIT License

public NetworkManager(Logger logger) {
    this.logger = logger;

    PacketRegistry packetRegistry = new PacketRegistry();
    HandlerRegistry handlerRegistry = new HandlerRegistry();
    SessionManager sessionManager = new SessionManager();
    this.nettyBootstrap.group(this.nettyBossGroup, this.nettyWorkerGroup).channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true)
            .childHandler(/*from   w ww  . j a  va2  s  .co  m*/
                    new ServerChannelInitializer(this.logger, sessionManager, packetRegistry, handlerRegistry));
}