Search in sources :

Example 51 with EventLoopGroup

use of org.apache.flink.shaded.netty4.io.netty.channel.EventLoopGroup in project tutorials-java by Artister.

the class HelloWorldClient method start.

public void start() {
    EventLoopGroup group = new NioEventLoopGroup();
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(group).channel(NioSocketChannel.class).handler(new ClientChannelInitializer());
    try {
        ChannelFuture future = bootstrap.connect(address, port).sync();
        future.channel().closeFuture().sync();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        group.shutdownGracefully();
    }
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) ClientChannelInitializer(org.ko.netty.t3.initializer.ClientChannelInitializer) ChannelFuture(io.netty.channel.ChannelFuture) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 52 with EventLoopGroup

use of org.apache.flink.shaded.netty4.io.netty.channel.EventLoopGroup in project java-driver by datastax.

the class NettyOptionsTest method should_invoke_netty_options_hooks.

private void should_invoke_netty_options_hooks(int hosts, int coreConnections) throws Exception {
    NettyOptions nettyOptions = mock(NettyOptions.class, CALLS_REAL_METHODS.get());
    EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
    Timer timer = new HashedWheelTimer();
    doReturn(eventLoopGroup).when(nettyOptions).eventLoopGroup(any(ThreadFactory.class));
    doReturn(timer).when(nettyOptions).timer(any(ThreadFactory.class));
    final ChannelHandler handler = mock(ChannelHandler.class);
    doAnswer(new Answer() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            SocketChannel channel = (SocketChannel) invocation.getArguments()[0];
            channel.pipeline().addLast("test-handler", handler);
            return null;
        }
    }).when(nettyOptions).afterChannelInitialized(any(SocketChannel.class));
    Cluster cluster = register(Cluster.builder().addContactPoints(getContactPoints().get(0)).withPort(ccm().getBinaryPort()).withPoolingOptions(new PoolingOptions().setConnectionsPerHost(HostDistance.LOCAL, coreConnections, coreConnections)).withNettyOptions(nettyOptions).build());
    // when
    // force session creation to populate pools
    cluster.connect();
    int expectedNumberOfCalls = TestUtils.numberOfLocalCoreConnections(cluster) * hosts + 1;
    // If the driver supports a more recent protocol version than C*, the negotiation at startup
    // will open an additional connection for each protocol version tried.
    ProtocolVersion version = ProtocolVersion.NEWEST_SUPPORTED;
    ProtocolVersion usedVersion = ccm().getProtocolVersion();
    while (version != usedVersion && version != null) {
        version = version.getLowerSupported();
        expectedNumberOfCalls++;
    }
    cluster.close();
    // then
    verify(nettyOptions, times(1)).eventLoopGroup(any(ThreadFactory.class));
    verify(nettyOptions, times(1)).channelClass();
    verify(nettyOptions, times(1)).timer(any(ThreadFactory.class));
    // per-connection hooks will be called coreConnections * hosts + 1 times:
    // the extra call is for the control connection
    verify(nettyOptions, times(expectedNumberOfCalls)).afterBootstrapInitialized(any(Bootstrap.class));
    verify(nettyOptions, times(expectedNumberOfCalls)).afterChannelInitialized(any(SocketChannel.class));
    verify(handler, times(expectedNumberOfCalls)).handlerAdded(any(ChannelHandlerContext.class));
    verify(handler, times(expectedNumberOfCalls)).handlerRemoved(any(ChannelHandlerContext.class));
    verify(nettyOptions, times(1)).onClusterClose(eventLoopGroup);
    verify(nettyOptions, times(1)).onClusterClose(timer);
    verifyNoMoreInteractions(nettyOptions);
}
Also used : ThreadFactory(java.util.concurrent.ThreadFactory) SocketChannel(io.netty.channel.socket.SocketChannel) HashedWheelTimer(io.netty.util.HashedWheelTimer) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelHandler(io.netty.channel.ChannelHandler) Answer(org.mockito.stubbing.Answer) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) HashedWheelTimer(io.netty.util.HashedWheelTimer) Timer(io.netty.util.Timer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 53 with EventLoopGroup

use of org.apache.flink.shaded.netty4.io.netty.channel.EventLoopGroup in project cosmic by MissionCriticalCloud.

the class NfsSecondaryStorageResource method startPostUploadServer.

private void startPostUploadServer() {
    final int PORT = 8210;
    final int NO_OF_WORKERS = 15;
    final EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    final EventLoopGroup workerGroup = new NioEventLoopGroup(NO_OF_WORKERS);
    final ServerBootstrap b = new ServerBootstrap();
    final NfsSecondaryStorageResource storageResource = this;
    b.group(bossGroup, workerGroup);
    b.channel(NioServerSocketChannel.class);
    b.handler(new LoggingHandler(LogLevel.INFO));
    b.childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(final SocketChannel ch) throws Exception {
            final ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast(new HttpRequestDecoder());
            pipeline.addLast(new HttpResponseEncoder());
            pipeline.addLast(new HttpContentCompressor());
            pipeline.addLast(new HttpUploadServerHandler(storageResource));
        }
    });
    new Thread() {

        @Override
        public void run() {
            try {
                final Channel ch = b.bind(PORT).sync().channel();
                s_logger.info(String.format("Started post upload server on port %d with %d workers", PORT, NO_OF_WORKERS));
                ch.closeFuture().sync();
            } catch (final InterruptedException e) {
                s_logger.info("Failed to start post upload server");
                s_logger.debug("Exception while starting post upload server", e);
            } finally {
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
                s_logger.info("shutting down post upload server");
            }
        }
    }.start();
    s_logger.info("created a thread to start post upload server");
}
Also used : SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) LoggingHandler(io.netty.handler.logging.LoggingHandler) HttpContentCompressor(io.netty.handler.codec.http.HttpContentCompressor) SocketChannel(io.netty.channel.socket.SocketChannel) Channel(io.netty.channel.Channel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) InternalErrorException(com.cloud.exception.InternalErrorException) ConfigurationException(javax.naming.ConfigurationException) ChannelPipeline(io.netty.channel.ChannelPipeline) HttpResponseEncoder(io.netty.handler.codec.http.HttpResponseEncoder) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) HttpRequestDecoder(io.netty.handler.codec.http.HttpRequestDecoder) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 54 with EventLoopGroup

use of org.apache.flink.shaded.netty4.io.netty.channel.EventLoopGroup in project autobahn-java by crossbario.

the class NettyWebSocket method connect.

@Override
public void connect(ITransportHandler transportHandler, TransportOptions options) throws Exception {
    if (options == null) {
        if (mOptions == null) {
            options = new TransportOptions();
        } else {
            options = new TransportOptions();
            options.setAutoPingInterval(mOptions.getAutoPingInterval());
            options.setAutoPingTimeout(mOptions.getAutoPingTimeout());
            options.setMaxFramePayloadSize(mOptions.getMaxFramePayloadSize());
        }
    }
    URI uri;
    uri = new URI(mUri);
    int port = validateURIAndGetPort(uri);
    String scheme = uri.getScheme();
    String host = uri.getHost();
    final SslContext sslContext = getSSLContext(scheme);
    WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, mSerializers, true, new DefaultHttpHeaders(), options.getMaxFramePayloadSize());
    mHandler = new NettyWebSocketClientHandler(handshaker, this, transportHandler);
    EventLoopGroup group = new NioEventLoopGroup();
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(group);
    bootstrap.channel(NioSocketChannel.class);
    TransportOptions opt = options;
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline channelPipeline = ch.pipeline();
            if (sslContext != null) {
                channelPipeline.addLast(sslContext.newHandler(ch.alloc(), host, port));
            }
            channelPipeline.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), WebSocketClientCompressionHandler.INSTANCE, new IdleStateHandler(opt.getAutoPingInterval() + opt.getAutoPingTimeout(), opt.getAutoPingInterval(), 0, TimeUnit.SECONDS), mHandler);
        }
    });
    mChannel = bootstrap.connect(uri.getHost(), port).sync().channel();
    mHandler.getHandshakeFuture().sync();
}
Also used : WebSocketClientHandshaker(io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) TransportOptions(io.crossbar.autobahn.wamp.types.TransportOptions) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) URI(java.net.URI) SSLException(javax.net.ssl.SSLException) ChannelPipeline(io.netty.channel.ChannelPipeline) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SslContext(io.netty.handler.ssl.SslContext)

Example 55 with EventLoopGroup

use of org.apache.flink.shaded.netty4.io.netty.channel.EventLoopGroup in project LogHub by fbacchella.

the class TestServer method testSimple.

@Test(timeout = 2000)
public void testSimple() throws InterruptedException {
    Properties empty = new Properties(Collections.emptyMap());
    BlockingQueue<Event> receiver = new ArrayBlockingQueue<>(1);
    TesterReceiver r = new TesterReceiver(receiver, new Pipeline(Collections.emptyList(), "testone", null));
    r.configure(empty);
    final ChannelFuture[] sent = new ChannelFuture[1];
    EventLoopGroup workerGroup = new DefaultEventLoopGroup();
    Bootstrap b = new Bootstrap();
    b.group(workerGroup);
    b.channel(LocalChannel.class);
    b.handler(new SimpleChannelInboundHandler<ByteBuf>() {

        @Override
        public void channelActive(ChannelHandlerContext ctx) {
            sent[0] = ctx.writeAndFlush(Unpooled.copiedBuffer("Message\r\n", CharsetUtil.UTF_8));
        }

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        }
    });
    // Start the client.
    ChannelFuture f = b.connect(new LocalAddress(TestServer.class.getCanonicalName())).sync();
    Thread.sleep(100);
    sent[0].sync();
    f.channel().close();
    // Wait until the connection is closed.
    f.channel().closeFuture().sync();
    Event e = receiver.poll();
    Assert.assertEquals("Message", e.get("message"));
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) LocalAddress(io.netty.channel.local.LocalAddress) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Properties(loghub.configuration.Properties) ByteBuf(io.netty.buffer.ByteBuf) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) IOException(java.io.IOException) Pipeline(loghub.Pipeline) ChannelPipeline(io.netty.channel.ChannelPipeline) EventLoopGroup(io.netty.channel.EventLoopGroup) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) Event(loghub.Event) AbstractBootstrap(io.netty.bootstrap.AbstractBootstrap) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) Test(org.junit.Test)

Aggregations

EventLoopGroup (io.netty.channel.EventLoopGroup)367 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)271 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)162 Bootstrap (io.netty.bootstrap.Bootstrap)137 Channel (io.netty.channel.Channel)131 ChannelFuture (io.netty.channel.ChannelFuture)129 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)109 SocketChannel (io.netty.channel.socket.SocketChannel)94 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)92 InetSocketAddress (java.net.InetSocketAddress)69 Test (org.junit.jupiter.api.Test)67 DefaultEventLoopGroup (io.netty.channel.DefaultEventLoopGroup)60 LoggingHandler (io.netty.handler.logging.LoggingHandler)55 ChannelPipeline (io.netty.channel.ChannelPipeline)51 SslContext (io.netty.handler.ssl.SslContext)51 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)50 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)49 SelfSignedCertificate (io.netty.handler.ssl.util.SelfSignedCertificate)46 LocalServerChannel (io.netty.channel.local.LocalServerChannel)42 LocalChannel (io.netty.channel.local.LocalChannel)40