Search in sources :

Example 1 with ChannelInitializer

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInitializer in project vert.x by eclipse.

the class HostnameResolutionTest method testAsyncResolveConnectIsNotifiedOnChannelEventLoop.

@Test
public void testAsyncResolveConnectIsNotifiedOnChannelEventLoop() throws Exception {
    CountDownLatch listenLatch = new CountDownLatch(1);
    NetServer s = vertx.createNetServer().connectHandler(so -> {
    });
    s.listen(1234, "localhost", onSuccess(v -> listenLatch.countDown()));
    awaitLatch(listenLatch);
    AtomicReference<Thread> channelThread = new AtomicReference<>();
    CountDownLatch connectLatch = new CountDownLatch(1);
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.group(vertx.nettyEventLoopGroup());
    bootstrap.resolver(((VertxInternal) vertx).nettyAddressResolverGroup());
    bootstrap.handler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            channelThread.set(Thread.currentThread());
            connectLatch.countDown();
        }
    });
    ChannelFuture channelFut = bootstrap.connect("localhost", 1234);
    awaitLatch(connectLatch);
    channelFut.addListener(v -> {
        assertTrue(v.isSuccess());
        assertEquals(channelThread.get(), Thread.currentThread());
        testComplete();
    });
    await();
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) VertxException(io.vertx.core.VertxException) Arrays(java.util.Arrays) HttpServer(io.vertx.core.http.HttpServer) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) AddressResolverOptions(io.vertx.core.dns.AddressResolverOptions) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) InetAddress(java.net.InetAddress) Locale(java.util.Locale) Map(java.util.Map) JsonObject(io.vertx.core.json.JsonObject) FakeDNSServer(io.vertx.test.fakedns.FakeDNSServer) NetClient(io.vertx.core.net.NetClient) VertxImpl(io.vertx.core.impl.VertxImpl) VertxInternal(io.vertx.core.impl.VertxInternal) ChannelInitializer(io.netty.channel.ChannelInitializer) AddressResolver(io.vertx.core.impl.AddressResolver) VertxOptions(io.vertx.core.VertxOptions) Test(org.junit.Test) InetSocketAddress(java.net.InetSocketAddress) UnknownHostException(java.net.UnknownHostException) File(java.io.File) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) TimeUnit(java.util.concurrent.TimeUnit) Bootstrap(io.netty.bootstrap.Bootstrap) CountDownLatch(java.util.concurrent.CountDownLatch) NetServerOptions(io.vertx.core.net.NetServerOptions) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) NetServer(io.vertx.core.net.NetServer) Collections(java.util.Collections) HttpClient(io.vertx.core.http.HttpClient) ChannelFuture(io.netty.channel.ChannelFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) Bootstrap(io.netty.bootstrap.Bootstrap) NetServer(io.vertx.core.net.NetServer) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) VertxException(io.vertx.core.VertxException) UnknownHostException(java.net.UnknownHostException) Test(org.junit.Test)

Example 2 with ChannelInitializer

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInitializer in project vert.x by eclipse.

the class HttpServerImpl method listen.

public synchronized HttpServer listen(int port, String host, Handler<AsyncResult<HttpServer>> listenHandler) {
    if (requestStream.handler() == null && wsStream.handler() == null) {
        throw new IllegalStateException("Set request or websocket handler first");
    }
    if (listening) {
        throw new IllegalStateException("Already listening");
    }
    listenContext = vertx.getOrCreateContext();
    listening = true;
    serverOrigin = (options.isSsl() ? "https" : "http") + "://" + host + ":" + port;
    List<HttpVersion> applicationProtocols = options.getAlpnVersions();
    if (listenContext.isWorkerContext()) {
        applicationProtocols = applicationProtocols.stream().filter(v -> v != HttpVersion.HTTP_2).collect(Collectors.toList());
    }
    sslHelper.setApplicationProtocols(applicationProtocols);
    synchronized (vertx.sharedHttpServers()) {
        // Will be updated on bind for a wildcard port
        this.actualPort = port;
        id = new ServerID(port, host);
        HttpServerImpl shared = vertx.sharedHttpServers().get(id);
        if (shared == null || port == 0) {
            serverChannelGroup = new DefaultChannelGroup("vertx-acceptor-channels", GlobalEventExecutor.INSTANCE);
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(vertx.getAcceptorEventLoopGroup(), availableWorkers);
            bootstrap.channel(NioServerSocketChannel.class);
            applyConnectionOptions(bootstrap);
            sslHelper.validate(vertx);
            bootstrap.childHandler(new ChannelInitializer<Channel>() {

                @Override
                protected void initChannel(Channel ch) throws Exception {
                    if (requestStream.isPaused() || wsStream.isPaused()) {
                        ch.close();
                        return;
                    }
                    ChannelPipeline pipeline = ch.pipeline();
                    if (sslHelper.isSSL()) {
                        pipeline.addLast("ssl", sslHelper.createSslHandler(vertx));
                        if (options.isUseAlpn()) {
                            pipeline.addLast("alpn", new ApplicationProtocolNegotiationHandler("http/1.1") {

                                @Override
                                protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception {
                                    if (protocol.equals("http/1.1")) {
                                        configureHttp1(pipeline);
                                    } else {
                                        handleHttp2(ch);
                                    }
                                }
                            });
                        } else {
                            configureHttp1(pipeline);
                        }
                    } else {
                        if (DISABLE_HC2) {
                            configureHttp1(pipeline);
                        } else {
                            pipeline.addLast(new Http1xOrHttp2Handler());
                        }
                    }
                }
            });
            addHandlers(this, listenContext);
            try {
                bindFuture = AsyncResolveConnectHelper.doBind(vertx, port, host, bootstrap);
                bindFuture.addListener(res -> {
                    if (res.failed()) {
                        vertx.sharedHttpServers().remove(id);
                    } else {
                        Channel serverChannel = res.result();
                        HttpServerImpl.this.actualPort = ((InetSocketAddress) serverChannel.localAddress()).getPort();
                        serverChannelGroup.add(serverChannel);
                        metrics = vertx.metricsSPI().createMetrics(this, new SocketAddressImpl(port, host), options);
                    }
                });
            } catch (final Throwable t) {
                // Make sure we send the exception back through the handler (if any)
                if (listenHandler != null) {
                    vertx.runOnContext(v -> listenHandler.handle(Future.failedFuture(t)));
                } else {
                    // No handler - log so user can see failure
                    log.error(t);
                }
                listening = false;
                return this;
            }
            vertx.sharedHttpServers().put(id, this);
            actualServer = this;
        } else {
            // Server already exists with that host/port - we will use that
            actualServer = shared;
            this.actualPort = shared.actualPort;
            addHandlers(actualServer, listenContext);
            metrics = vertx.metricsSPI().createMetrics(this, new SocketAddressImpl(port, host), options);
        }
        actualServer.bindFuture.addListener(future -> {
            if (listenHandler != null) {
                final AsyncResult<HttpServer> res;
                if (future.succeeded()) {
                    res = Future.succeededFuture(HttpServerImpl.this);
                } else {
                    res = Future.failedFuture(future.cause());
                    listening = false;
                }
                listenContext.runOnContext((v) -> listenHandler.handle(res));
            } else if (future.failed()) {
                listening = false;
                log.error(future.cause());
            }
        });
    }
    return this;
}
Also used : DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) VertxException(io.vertx.core.VertxException) HandlerManager(io.vertx.core.net.impl.HandlerManager) ServerWebSocket(io.vertx.core.http.ServerWebSocket) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) WebSocketServerHandshakerFactory(io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) HttpServer(io.vertx.core.http.HttpServer) URISyntaxException(java.net.URISyntaxException) ChunkedWriteHandler(io.netty.handler.stream.ChunkedWriteHandler) Unpooled(io.netty.buffer.Unpooled) GlobalEventExecutor(io.netty.util.concurrent.GlobalEventExecutor) HttpServerMetrics(io.vertx.core.spi.metrics.HttpServerMetrics) HttpVersion(io.vertx.core.http.HttpVersion) Http2Exception(io.netty.handler.codec.http2.Http2Exception) Map(java.util.Map) ApplicationProtocolNegotiationHandler(io.netty.handler.ssl.ApplicationProtocolNegotiationHandler) CharsetUtil(io.netty.util.CharsetUtil) ReadStream(io.vertx.core.streams.ReadStream) WebSocketFrameImpl(io.vertx.core.http.impl.ws.WebSocketFrameImpl) URI(java.net.URI) Logger(io.vertx.core.logging.Logger) ChannelGroup(io.netty.channel.group.ChannelGroup) HttpRequest(io.netty.handler.codec.http.HttpRequest) ChannelInitializer(io.netty.channel.ChannelInitializer) PartialPooledByteBufAllocator(io.vertx.core.net.impl.PartialPooledByteBufAllocator) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) MetricsProvider(io.vertx.core.spi.metrics.MetricsProvider) ChannelPipeline(io.netty.channel.ChannelPipeline) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) Future(io.vertx.core.Future) ServerID(io.vertx.core.net.impl.ServerID) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) SslHandler(io.netty.handler.ssl.SslHandler) HandlerHolder(io.vertx.core.net.impl.HandlerHolder) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) WebSocketFrameInternal(io.vertx.core.http.impl.ws.WebSocketFrameInternal) VertxEventLoopGroup(io.vertx.core.net.impl.VertxEventLoopGroup) HttpServerRequest(io.vertx.core.http.HttpServerRequest) HttpVersion(io.netty.handler.codec.http.HttpVersion) ChannelOption(io.netty.channel.ChannelOption) LoggingHandler(io.netty.handler.logging.LoggingHandler) ContextImpl(io.vertx.core.impl.ContextImpl) FlashPolicyHandler(io.vertx.core.http.impl.cgbystrom.FlashPolicyHandler) WebSocketHandshakeException(io.netty.handler.codec.http.websocketx.WebSocketHandshakeException) LoggerFactory(io.vertx.core.logging.LoggerFactory) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) WebSocketVersion(io.netty.handler.codec.http.websocketx.WebSocketVersion) ByteBuf(io.netty.buffer.ByteBuf) FixedRecvByteBufAllocator(io.netty.channel.FixedRecvByteBufAllocator) ChannelFutureListener(io.netty.channel.ChannelFutureListener) AsyncResult(io.vertx.core.AsyncResult) HttpConnection(io.vertx.core.http.HttpConnection) Metrics(io.vertx.core.spi.metrics.Metrics) HttpContent(io.netty.handler.codec.http.HttpContent) Closeable(io.vertx.core.Closeable) VertxInternal(io.vertx.core.impl.VertxInternal) HttpHeaderValues(io.netty.handler.codec.http.HttpHeaderValues) AsyncResolveConnectHelper(io.vertx.core.net.impl.AsyncResolveConnectHelper) HttpMethod(io.netty.handler.codec.http.HttpMethod) SSLHelper(io.vertx.core.net.impl.SSLHelper) Channel(io.netty.channel.Channel) Http2Settings(io.netty.handler.codec.http2.Http2Settings) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) WebSocketServerHandshaker(io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) HttpServerOptions(io.vertx.core.http.HttpServerOptions) ChannelHandler(io.netty.channel.ChannelHandler) ChannelGroupFuture(io.netty.channel.group.ChannelGroupFuture) HttpContentDecompressor(io.netty.handler.codec.http.HttpContentDecompressor) HttpRequestDecoder(io.netty.handler.codec.http.HttpRequestDecoder) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Handler(io.vertx.core.Handler) SocketAddressImpl(io.vertx.core.net.impl.SocketAddressImpl) Http2CodecUtil(io.netty.handler.codec.http2.Http2CodecUtil) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) VertxException(io.vertx.core.VertxException) URISyntaxException(java.net.URISyntaxException) Http2Exception(io.netty.handler.codec.http2.Http2Exception) WebSocketHandshakeException(io.netty.handler.codec.http.websocketx.WebSocketHandshakeException) ChannelPipeline(io.netty.channel.ChannelPipeline) ApplicationProtocolNegotiationHandler(io.netty.handler.ssl.ApplicationProtocolNegotiationHandler) ServerID(io.vertx.core.net.impl.ServerID) HttpServer(io.vertx.core.http.HttpServer) SocketAddressImpl(io.vertx.core.net.impl.SocketAddressImpl) HttpVersion(io.vertx.core.http.HttpVersion) HttpVersion(io.netty.handler.codec.http.HttpVersion)

Example 3 with ChannelInitializer

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInitializer in project intellij-community by JetBrains.

the class BuildManager method startListening.

private int startListening() throws Exception {
    EventLoopGroup group;
    BuiltInServer mainServer = StartupUtil.getServer();
    boolean isOwnEventLoopGroup = !Registry.is("compiler.shared.event.group", true) || mainServer == null || mainServer.getEventLoopGroup() instanceof OioEventLoopGroup;
    if (isOwnEventLoopGroup) {
        group = new NioEventLoopGroup(1, ConcurrencyUtil.newNamedThreadFactory("External compiler"));
    } else {
        group = mainServer.getEventLoopGroup();
    }
    final ServerBootstrap bootstrap = serverBootstrap(group);
    bootstrap.childHandler(new ChannelInitializer() {

        @Override
        protected void initChannel(@NotNull Channel channel) throws Exception {
            channel.pipeline().addLast(myChannelRegistrar, new ProtobufVarint32FrameDecoder(), new ProtobufDecoder(CmdlineRemoteProto.Message.getDefaultInstance()), new ProtobufVarint32LengthFieldPrepender(), new ProtobufEncoder(), myMessageDispatcher);
        }
    });
    Channel serverChannel = bootstrap.bind(InetAddress.getLoopbackAddress(), 0).syncUninterruptibly().channel();
    myChannelRegistrar.setServerChannel(serverChannel, isOwnEventLoopGroup);
    return ((InetSocketAddress) serverChannel.localAddress()).getPort();
}
Also used : ProtobufEncoder(io.netty.handler.codec.protobuf.ProtobufEncoder) OioEventLoopGroup(io.netty.channel.oio.OioEventLoopGroup) InetSocketAddress(java.net.InetSocketAddress) Channel(io.netty.channel.Channel) ProtobufDecoder(io.netty.handler.codec.protobuf.ProtobufDecoder) ProtobufVarint32LengthFieldPrepender(io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender) BuiltInServer(org.jetbrains.io.BuiltInServer) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) IOException(java.io.IOException) ExecutionException(com.intellij.execution.ExecutionException) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) OioEventLoopGroup(io.netty.channel.oio.OioEventLoopGroup) ChannelInitializer(io.netty.channel.ChannelInitializer) ProtobufVarint32FrameDecoder(io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 4 with ChannelInitializer

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInitializer in project intellij-community by JetBrains.

the class SubServer method bind.

public boolean bind(int port) {
    if (port == server.getPort() || port == -1) {
        return true;
    }
    if (channelRegistrar == null) {
        Disposer.register(server, this);
        channelRegistrar = new ChannelRegistrar();
    }
    ServerBootstrap bootstrap = serverBootstrap(server.getEventLoopGroup());
    Map<String, Object> xmlRpcHandlers = user.createXmlRpcHandlers();
    if (xmlRpcHandlers == null) {
        BuiltInServer.configureChildHandler(bootstrap, channelRegistrar, null);
    } else {
        final XmlRpcDelegatingHttpRequestHandler handler = new XmlRpcDelegatingHttpRequestHandler(xmlRpcHandlers);
        bootstrap.childHandler(new ChannelInitializer() {

            @Override
            protected void initChannel(Channel channel) throws Exception {
                channel.pipeline().addLast(channelRegistrar);
                NettyUtil.addHttpServerCodec(channel.pipeline());
                channel.pipeline().addLast(handler);
            }
        });
    }
    try {
        bootstrap.localAddress(user.isAvailableExternally() ? new InetSocketAddress(port) : NetKt.loopbackSocketAddress(port));
        channelRegistrar.setServerChannel(bootstrap.bind().syncUninterruptibly().channel(), false);
        return true;
    } catch (Exception e) {
        try {
            NettyUtil.log(e, Logger.getInstance(BuiltInServer.class));
        } finally {
            user.cannotBind(e, port);
        }
        return false;
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) Channel(io.netty.channel.Channel) ChannelInitializer(io.netty.channel.ChannelInitializer) ServerBootstrap(io.netty.bootstrap.ServerBootstrap)

Example 5 with ChannelInitializer

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInitializer in project camel by apache.

the class NettyUDPByteArrayProviderTest method createNettyUdpReceiver.

public void createNettyUdpReceiver() {
    group = new NioEventLoopGroup();
    bootstrap = new Bootstrap();
    bootstrap.group(group).channel(NioDatagramChannel.class).handler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel channel) throws Exception {
            channel.pipeline().addLast(new UdpHandler());
            channel.pipeline().addLast(new ByteArrayDecoder());
            channel.pipeline().addLast(new ContentHandler());
        }
    }).localAddress(new InetSocketAddress(getPort()));
}
Also used : InetSocketAddress(java.net.InetSocketAddress) Channel(io.netty.channel.Channel) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) Bootstrap(io.netty.bootstrap.Bootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ByteArrayDecoder(io.netty.handler.codec.bytes.ByteArrayDecoder)

Aggregations

ChannelInitializer (io.netty.channel.ChannelInitializer)83 Channel (io.netty.channel.Channel)58 Bootstrap (io.netty.bootstrap.Bootstrap)42 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)39 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)36 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)32 InetSocketAddress (java.net.InetSocketAddress)32 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)31 ChannelFuture (io.netty.channel.ChannelFuture)29 EventLoopGroup (io.netty.channel.EventLoopGroup)26 ChannelPipeline (io.netty.channel.ChannelPipeline)25 LocalServerChannel (io.netty.channel.local.LocalServerChannel)22 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)21 LocalChannel (io.netty.channel.local.LocalChannel)20 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)17 SslHandler (io.netty.handler.ssl.SslHandler)17 SocketChannel (io.netty.channel.socket.SocketChannel)16 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)14 DefaultEventLoopGroup (io.netty.channel.DefaultEventLoopGroup)12 CountDownLatch (java.util.concurrent.CountDownLatch)12