Example usage for io.netty.channel Channel config

List of usage examples for io.netty.channel Channel config

Introduction

In this page you can find the example usage for io.netty.channel Channel config.

Prototype

ChannelConfig config();

Source Link

Document

Returns the configuration of this channel.

Usage

From source file:at.yawk.dbus.protocol.DbusConnector.java

public DbusConnector() {
    bootstrap = new Bootstrap();
    bootstrap.handler(new ChannelInitializer<Channel>() {
        @Override/*from  w  ww .  j ava  2s . c o m*/
        protected void initChannel(Channel ch) throws Exception {
            ch.config().setAutoRead(false);
        }
    });
}

From source file:at.yawk.dbus.protocol.DbusConnector.java

/**
 * Connect to the dbus server at the given {@link SocketAddress}.
 *//*  www . j a  v a2s  .  co m*/
public DbusChannel connect(SocketAddress address) throws Exception {
    Bootstrap localBootstrap = bootstrap.clone();
    if (address instanceof DomainSocketAddress) {
        localBootstrap.group(new EpollEventLoopGroup());
        localBootstrap.channel(EpollDomainSocketChannel.class);
    } else {
        localBootstrap.group(new NioEventLoopGroup());
        localBootstrap.channel(NioSocketChannel.class);
    }

    Channel channel = localBootstrap.connect(address).sync().channel();

    AuthClient authClient = new AuthClient();
    if (LoggingInboundAdapter.isEnabled()) {
        channel.pipeline().addLast(new LoggingInboundAdapter());
    }

    channel.pipeline().addLast("auth", authClient);
    channel.config().setAutoRead(true);
    log.trace("Pipeline is now {}", channel.pipeline());

    // I really don't get why dbus does this
    channel.write(Unpooled.wrappedBuffer(new byte[] { 0 }));

    if (authMechanism == null) {
        authMechanism = new ExternalAuthMechanism();
    }
    CompletionStage<?> completionPromise = authClient.startAuth(channel, authMechanism);

    SwappableMessageConsumer swappableConsumer = new SwappableMessageConsumer(initialConsumer);
    completionPromise.toCompletableFuture().thenRun(() -> {
        channel.pipeline().replace("auth", "main", new DbusMainProtocol(swappableConsumer));
        log.trace("Pipeline is now {}", channel.pipeline());
    }).get();

    DbusChannelImpl dbusChannel = new DbusChannelImpl(channel, swappableConsumer);

    dbusChannel.write(MessageFactory.methodCall("/", "org.freedesktop.DBus", "org.freedesktop.DBus", "Hello"));

    return dbusChannel;
}

From source file:catacumba.websocket.internal.WebSocketEngine.java

License:Apache License

@SuppressWarnings("deprecation")
public static <T> void connect(final Context context, String path, int maxLength,
        final WebSocketHandler<T> handler) {
    PublicAddress publicAddress = context.get(PublicAddress.class);
    URI address = publicAddress.get(context);
    URI httpPath = address.resolve(path);

    URI wsPath;//from ww w  .j  av a2  s  .  c o m
    try {
        wsPath = new URI("ws", httpPath.getUserInfo(), httpPath.getHost(), httpPath.getPort(),
                httpPath.getPath(), httpPath.getQuery(), httpPath.getFragment());
    } catch (URISyntaxException e) {
        throw uncheck(e);
    }

    WebSocketServerHandshakerFactory factory = new WebSocketServerHandshakerFactory(wsPath.toString(), null,
            true, maxLength);

    Request request = context.getRequest();
    HttpMethod method = valueOf(request.getMethod().getName());
    FullHttpRequest nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, method, request.getUri());
    nettyRequest.headers().add(SEC_WEBSOCKET_VERSION, request.getHeaders().get(SEC_WEBSOCKET_VERSION));
    nettyRequest.headers().add(SEC_WEBSOCKET_KEY, request.getHeaders().get(SEC_WEBSOCKET_KEY));

    final WebSocketServerHandshaker handshaker = factory.newHandshaker(nettyRequest);

    final DirectChannelAccess directChannelAccess = context.getDirectChannelAccess();
    final Channel channel = directChannelAccess.getChannel();

    if (!channel.config().isAutoRead()) {
        channel.config().setAutoRead(true);
    }

    handshaker.handshake(channel, nettyRequest)
            .addListener(new HandshakeFutureListener<>(context, handshaker, handler));
}

From source file:com.cloudhopper.smpp.impl.DefaultSmppServer.java

License:Apache License

protected void createSession(Long sessionId, Channel channel, SmppSessionConfiguration config,
        BaseBindResp preparedBindResponse) throws SmppProcessingException {
    // NOTE: exactly one PDU (bind request) was read from the channel, we
    // now need to delegate permitting this bind request by calling a method
    // further upstream.  Only after the server-side is completely ready to
    // start processing requests from this session, do we want to actually
    // return the bind response and start reading further requests -- we'll
    // initially block reading from the channel first -- this will be turned
    // back on via the "serverReady()" method call on the session object

    // make sure the channel is not being read/processed (until we flag we're ready later on)
    channel.config().setAutoRead(false);

    // auto negotiate the interface version in use based on the requested interface version
    byte interfaceVersion = this.autoNegotiateInterfaceVersion(config.getInterfaceVersion());

    // create a new server session associated with this server
    DefaultSmppSession session = new DefaultSmppSession(SmppSession.Type.SERVER, config, channel, this,
            sessionId, preparedBindResponse, interfaceVersion, monitorExecutor);

    // replace name of thread used for renaming
    SmppSessionThreadRenamer threadRenamer = (SmppSessionThreadRenamer) channel.pipeline()
            .get(SmppChannelConstants.PIPELINE_SESSION_THREAD_RENAMER_NAME);
    threadRenamer.setThreadName(config.getName());

    // add a logging handler after the thread renamer
    SmppSessionLogger loggingHandler = new SmppSessionLogger(DefaultSmppSession.class.getCanonicalName(),
            config.getLoggingOptions());
    channel.pipeline().addAfter(SmppChannelConstants.PIPELINE_SESSION_THREAD_RENAMER_NAME,
            SmppChannelConstants.PIPELINE_SESSION_LOGGER_NAME, loggingHandler);

    // decoder in pipeline is ok (keep it)

    // create a new wrapper around a session to pass the pdu up the chain
    channel.pipeline().remove(SmppChannelConstants.PIPELINE_SESSION_WRAPPER_NAME);
    channel.pipeline().addLast(SmppChannelConstants.PIPELINE_SESSION_WRAPPER_NAME,
            new SmppSessionWrapper(session));

    // check if the # of channels exceeds maxConnections
    if (this.channels.size() > this.configuration.getMaxConnectionSize()) {
        logger.warn("The current connection size [{}] exceeds the configured max connection size [{}]",
                this.channels.size(), this.configuration.getMaxConnectionSize());
    }//w  w w .j  ava2  s .  c  o m

    // session created, now pass it upstream
    counters.incrementSessionCreatedAndGet();
    incrementSessionSizeCounters(session);
    this.serverHandler.sessionCreated(sessionId, session, preparedBindResponse);

    // register this session as an mbean
    if (configuration.isJmxEnabled()) {
        session.registerMBean(configuration.getJmxDomain() + ":type=" + configuration.getName()
                + "Sessions,name=" + sessionId);
    }
}

From source file:com.github.sinsinpub.pero.backend.RelayTrafficHandler.java

License:Apache License

final MessageSizeEstimator.Handle estimatorHandle(Channel channel) {
    if (estimatorHandle == null) {
        estimatorHandle = channel.config().getMessageSizeEstimator().newHandle();
    }/*ww  w.  j  a v a  2s . c  o  m*/
    return estimatorHandle;
}

From source file:com.linecorp.armeria.internal.ConnectionLimitingHandler.java

License:Apache License

@Override
@SuppressWarnings("unchecked")
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    final Channel child = (Channel) msg;

    int conn = numConnections.incrementAndGet();
    if (conn > 0 && conn <= maxNumConnections) {
        childChannels.add(child);/*from   www  .j a  va 2 s  . co m*/
        child.closeFuture().addListener(future -> {
            childChannels.remove(child);
            numConnections.decrementAndGet();
        });
        super.channelRead(ctx, msg);
    } else {
        numConnections.decrementAndGet();

        // Set linger option to 0 so that the server doesn't get too many TIME_WAIT states.
        child.config().setOption(ChannelOption.SO_LINGER, 0);
        child.unsafe().closeForcibly();

        numDroppedConnections.increment();

        if (loggingScheduled.compareAndSet(false, true)) {
            ctx.executor().schedule(this::writeNumDroppedConnectionsLog, 1, TimeUnit.SECONDS);
        }
    }
}

From source file:com.linecorp.armeria.internal.InboundTrafficController.java

License:Apache License

public InboundTrafficController(@Nullable Channel channel, int highWatermark, int lowWatermark) {
    cfg = channel != null ? channel.config() : null;
    this.highWatermark = highWatermark;
    this.lowWatermark = lowWatermark;
}

From source file:com.linkedin.mitm.proxy.channel.ChannelMediator.java

License:Open Source License

/**
 * Create {@link io.netty.handler.ssl.SslHandler} and send TCP handshaking using
 * {@link javax.net.ssl.SSLEngine}//from w  w  w.j  a v a  2  s. c o m
 * After add ssl handler to the end of {@link io.netty.channel.ChannelPipeline}, it enable
 * secure communications over SSL/TLS
 *
 * @param isSslClient true if the channel start handshaking or false if accept handshaking
 * @param channel the channel to start handshaking
 * */
private Future<Channel> handshake(SSLEngine sslEngine, boolean isSslClient, Channel channel) {
    sslEngine.setUseClientMode(isSslClient);
    if (channel != null) {
        channel.config().setAutoRead(true);
    }
    SslHandler handler = new SslHandler(sslEngine);
    channel.pipeline().addFirst("ssl", handler);
    LOG.debug("About to start handshaking...");
    return handler.handshakeFuture();
}

From source file:com.linkedin.r2.transport.http.client.ChannelPoolLifecycle.java

License:Apache License

@Override
public void create(final Callback<Channel> channelCallback) {
    final long start = System.currentTimeMillis();
    _bootstrap.connect(_remoteAddress).addListener(new ChannelFutureListener() {
        @Override//  ww  w . j  a v  a 2 s  .c o m
        public void operationComplete(ChannelFuture channelFuture) throws Exception {
            if (channelFuture.isSuccess()) {
                synchronized (_createTimeTracker) {
                    _createTimeTracker.addValue(System.currentTimeMillis() - start);
                }
                Channel c = channelFuture.channel();
                if (_tcpNoDelay) {
                    c.config().setOption(ChannelOption.TCP_NODELAY, true);
                }
                _channelGroup.add(c);
                channelCallback.onSuccess(c);
            } else {
                channelCallback.onError(HttpNettyStreamClient.toException(channelFuture.cause()));
            }
        }
    });
}

From source file:com.virjar.dungproxy.server.proxyservice.client.listener.NettyConnectionsPool.java

License:Open Source License

/**
 * {@inheritDoc}//from ww  w.j  av a 2  s . c  o  m
 */
public boolean offer(String uri, Channel channel) {
    if (isClosed.get())
        return false;

    if (!sslConnectionPoolEnabled && uri.startsWith("https")) {
        return false;
    }

    if (maxConnectionLifeTimeInMs != -1) {
        Long createTime = channel2CreationDate.get(channel);
        if (createTime == null) {
            channel2CreationDate.putIfAbsent(channel, millisTime());
        } else if (createTime + maxConnectionLifeTimeInMs < millisTime()) {
            log.debug("Channel {} expired", channel);
            return false;
        }
    }

    log.debug("Adding uri: {} for channel {}", uri, channel);

    ConcurrentLinkedQueue<IdleChannel> idleConnectionForHost = connectionsPool.get(uri);
    if (idleConnectionForHost == null) {
        ConcurrentLinkedQueue<IdleChannel> newPool = new ConcurrentLinkedQueue<IdleChannel>();
        idleConnectionForHost = connectionsPool.putIfAbsent(uri, newPool);
        if (idleConnectionForHost == null)
            idleConnectionForHost = newPool;
    }

    boolean added;
    int size = idleConnectionForHost.size();
    if (maxConnectionPerHost == -1 || size < maxConnectionPerHost) {
        IdleChannel idleChannel = new IdleChannel(uri, channel);
        synchronized (idleConnectionForHost) {
            added = idleConnectionForHost.add(idleChannel);

            if (channel2IdleChannel.put(channel, idleChannel) != null) {
                log.error("Channel {} already exists in the connections pool!", channel);
            }
        }
    } else {
        log.debug("Maximum number of requests per host reached {} for {}", maxConnectionPerHost, uri);
        added = false;
    }
    if (added) {
        log.debug("offer connection, uri: {}", uri);
    }
    if (added) {
        // ? autoRead, ? channel ??
        channel.config().setAutoRead(true);
    }
    return added;
}