Search in sources :

Example 66 with ChannelInitializer

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInitializer in project proxyee-down by monkeyWie.

the class HttpDownUtil method getResponse.

/**
 * 取请求响应
 */
public static HttpResponse getResponse(HttpRequest httpRequest, ProxyConfig proxyConfig, SslContext clientSslCtx, NioEventLoopGroup loopGroup) throws Exception {
    final HttpResponse[] httpResponses = new HttpResponse[1];
    CountDownLatch cdl = new CountDownLatch(1);
    HttpRequestInfo requestInfo = (HttpRequestInfo) httpRequest;
    RequestProto requestProto = requestInfo.requestProto();
    Bootstrap bootstrap = new Bootstrap();
    // 注册线程池
    bootstrap.group(loopGroup).channel(// 使用NioSocketChannel来作为连接用的channel类
    NioSocketChannel.class).handler(new ChannelInitializer() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            if (proxyConfig != null) {
                ch.pipeline().addLast(ProxyHandleFactory.build(proxyConfig));
            }
            if (requestProto.getSsl()) {
                ch.pipeline().addLast(clientSslCtx.newHandler(ch.alloc()));
            }
            ch.pipeline().addLast("httpCodec", new HttpClientCodec());
            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                @Override
                public void channelRead(ChannelHandlerContext ctx0, Object msg0) throws Exception {
                    if (msg0 instanceof HttpResponse) {
                        HttpResponse httpResponse = (HttpResponse) msg0;
                        httpResponses[0] = httpResponse;
                        ctx0.channel().close();
                        cdl.countDown();
                    }
                }
            });
        }
    });
    if (proxyConfig != null) {
        // 代理服务器解析DNS和连接
        bootstrap.resolver(NoopAddressResolverGroup.INSTANCE);
    }
    ChannelFuture cf = bootstrap.connect(requestProto.getHost(), requestProto.getPort());
    cf.addListener((ChannelFutureListener) future -> {
        if (future.isSuccess()) {
            httpRequest.headers().set(HttpHeaderNames.RANGE, "bytes=0-0");
            cf.channel().writeAndFlush(httpRequest);
            if (requestInfo.content() != null) {
                HttpContent content = new DefaultLastHttpContent();
                content.content().writeBytes(requestInfo.content());
                cf.channel().writeAndFlush(content);
            }
        } else {
            cdl.countDown();
        }
    });
    cdl.await(30, TimeUnit.SECONDS);
    if (httpResponses[0] == null) {
        throw new TimeoutException("getResponse timeout");
    }
    return httpResponses[0];
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) ProxyConfig(lee.study.proxyee.proxy.ProxyConfig) ProxyHandleFactory(lee.study.proxyee.proxy.ProxyHandleFactory) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) URLDecoder(java.net.URLDecoder) URL(java.net.URL) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) TimeoutException(java.util.concurrent.TimeoutException) RequestProto(lee.study.proxyee.util.ProtoUtil.RequestProto) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) NoopAddressResolverGroup(io.netty.resolver.NoopAddressResolverGroup) TaskInfo(lee.study.down.model.TaskInfo) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Matcher(java.util.regex.Matcher) HttpHeadsInfo(lee.study.down.model.HttpHeadsInfo) HttpVer(lee.study.down.model.HttpRequestInfo.HttpVer) ChannelFutureListener(io.netty.channel.ChannelFutureListener) Map(java.util.Map) HttpContent(io.netty.handler.codec.http.HttpContent) HttpRequest(io.netty.handler.codec.http.HttpRequest) ChannelInitializer(io.netty.channel.ChannelInitializer) SslContext(io.netty.handler.ssl.SslContext) MalformedURLException(java.net.MalformedURLException) HttpRequestInfo(lee.study.down.model.HttpRequestInfo) HttpMethod(io.netty.handler.codec.http.HttpMethod) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) IOException(java.io.IOException) UUID(java.util.UUID) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) 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) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) Closeable(java.io.Closeable) Entry(java.util.Map.Entry) HttpResponse(io.netty.handler.codec.http.HttpResponse) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Pattern(java.util.regex.Pattern) ProtoUtil(lee.study.proxyee.util.ProtoUtil) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) HttpResponse(io.netty.handler.codec.http.HttpResponse) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) HttpRequestInfo(lee.study.down.model.HttpRequestInfo) CountDownLatch(java.util.concurrent.CountDownLatch) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) TimeoutException(java.util.concurrent.TimeoutException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) Bootstrap(io.netty.bootstrap.Bootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) RequestProto(lee.study.proxyee.util.ProtoUtil.RequestProto) HttpContent(io.netty.handler.codec.http.HttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) TimeoutException(java.util.concurrent.TimeoutException)

Example 67 with ChannelInitializer

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

the class RconServer method init0.

@Override
protected ChannelFuture init0(SocketAddress address, boolean epoll) {
    this.address = (InetSocketAddress) address;
    this.bootstrap = new ServerBootstrap();
    this.bossGroup = createEventLoopGroup(epoll);
    this.workerGroup = createEventLoopGroup(epoll);
    return this.bootstrap.group(this.bossGroup, this.workerGroup).channel(getServerSocketChannelClass(epoll)).childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new RconFramingHandler()).addLast(new RconHandler(RconServer.this, password));
        }
    }).bind(address);
}
Also used : SocketChannel(io.netty.channel.socket.SocketChannel) ChannelInitializer(io.netty.channel.ChannelInitializer) ServerBootstrap(io.netty.bootstrap.ServerBootstrap)

Example 68 with ChannelInitializer

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

the class SocketTransport method channelInitializer.

@Override
public ChannelInitializer<Channel> channelInitializer() {
    return new ChannelInitializer<>() {

        @Override
        public void initChannel(Channel ch) {
            ch.config().setAllocator(allocator);
            var memoryTracker = new LocalMemoryTracker(memoryPool, 0, 64, null);
            ch.closeFuture().addListener(future -> memoryTracker.close());
            memoryTracker.allocateHeap(HeapEstimator.sizeOf(ch));
            memoryTracker.allocateHeap(UnauthenticatedChannelProtector.SHALLOW_SIZE + BoltChannel.SHALLOW_SIZE);
            var channelProtector = new UnauthenticatedChannelProtector(ch, channelTimeout, maxMessageSize, memoryTracker);
            BoltChannel boltChannel = newBoltChannel(ch, channelProtector, memoryTracker);
            connectionTracker.add(boltChannel);
            ch.closeFuture().addListener(future -> connectionTracker.remove(boltChannel));
            // install throttles
            throttleGroup.install(ch, memoryTracker);
            // add a close listener that will uninstall throttles
            ch.closeFuture().addListener(future -> throttleGroup.uninstall(ch));
            memoryTracker.allocateHeap(TransportSelectionHandler.SHALLOW_SIZE);
            TransportSelectionHandler transportSelectionHandler = new TransportSelectionHandler(boltChannel, sslCtx, encryptionRequired, false, logging, boltProtocolFactory, channelProtector, memoryTracker);
            ch.pipeline().addLast(transportSelectionHandler);
        }
    };
}
Also used : UnauthenticatedChannelProtector(org.neo4j.bolt.transport.pipeline.UnauthenticatedChannelProtector) BoltChannel(org.neo4j.bolt.BoltChannel) Channel(io.netty.channel.Channel) LocalMemoryTracker(org.neo4j.memory.LocalMemoryTracker) BoltChannel(org.neo4j.bolt.BoltChannel) ChannelInitializer(io.netty.channel.ChannelInitializer)

Example 69 with ChannelInitializer

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

the class CleartextHttp2ServerUpgradeHandlerTest method usedHttp2MultiplexCodec.

@Test
public void usedHttp2MultiplexCodec() throws Exception {
    final Http2MultiplexCodec http2Codec = new Http2MultiplexCodecBuilder(true, new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
        }
    }).build();
    UpgradeCodecFactory upgradeCodecFactory = new UpgradeCodecFactory() {

        @Override
        public UpgradeCodec newUpgradeCodec(CharSequence protocol) {
            return new Http2ServerUpgradeCodec(http2Codec);
        }
    };
    http2ConnectionHandler = http2Codec;
    userEvents = new ArrayList<Object>();
    HttpServerCodec httpServerCodec = new HttpServerCodec();
    HttpServerUpgradeHandler upgradeHandler = new HttpServerUpgradeHandler(httpServerCodec, upgradeCodecFactory);
    CleartextHttp2ServerUpgradeHandler handler = new CleartextHttp2ServerUpgradeHandler(httpServerCodec, upgradeHandler, http2Codec);
    channel = new EmbeddedChannel(handler, new ChannelInboundHandlerAdapter() {

        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            userEvents.add(evt);
        }
    });
    assertFalse(channel.writeInbound(Http2CodecUtil.connectionPrefaceBuf()));
    ByteBuf settingsFrame = settingsFrameBuf();
    assertTrue(channel.writeInbound(settingsFrame));
    assertEquals(1, userEvents.size());
    assertTrue(userEvents.get(0) instanceof PriorKnowledgeUpgradeEvent);
}
Also used : PriorKnowledgeUpgradeEvent(io.netty.handler.codec.http2.CleartextHttp2ServerUpgradeHandler.PriorKnowledgeUpgradeEvent) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Channel(io.netty.channel.Channel) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) UpgradeCodecFactory(io.netty.handler.codec.http.HttpServerUpgradeHandler.UpgradeCodecFactory) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) HttpServerUpgradeHandler(io.netty.handler.codec.http.HttpServerUpgradeHandler) ByteBuf(io.netty.buffer.ByteBuf) HttpServerCodec(io.netty.handler.codec.http.HttpServerCodec) ChannelInitializer(io.netty.channel.ChannelInitializer) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test)

Example 70 with ChannelInitializer

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

the class HttpProxyHandlerTest method testExceptionDuringConnect.

@Test
public void testExceptionDuringConnect() throws Exception {
    EventLoopGroup group = null;
    Channel serverChannel = null;
    Channel clientChannel = null;
    try {
        group = new DefaultEventLoopGroup(1);
        final LocalAddress addr = new LocalAddress("a");
        final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
        ChannelFuture sf = new ServerBootstrap().channel(LocalServerChannel.class).group(group).childHandler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) {
                ch.pipeline().addFirst(new HttpResponseEncoder());
                DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_GATEWAY);
                response.headers().add("name", "value");
                response.headers().add(HttpHeaderNames.CONTENT_LENGTH, "0");
                ch.writeAndFlush(response);
            }
        }).bind(addr);
        serverChannel = sf.sync().channel();
        ChannelFuture cf = new Bootstrap().channel(LocalChannel.class).group(group).handler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) {
                ch.pipeline().addFirst(new HttpProxyHandler(addr));
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                        exception.set(cause);
                    }
                });
            }
        }).connect(new InetSocketAddress("localhost", 1234));
        clientChannel = cf.sync().channel();
        clientChannel.close().sync();
        assertTrue(exception.get() instanceof HttpProxyConnectException);
        HttpProxyConnectException actual = (HttpProxyConnectException) exception.get();
        assertNotNull(actual.headers());
        assertEquals("value", actual.headers().get("name"));
    } finally {
        if (clientChannel != null) {
            clientChannel.close();
        }
        if (serverChannel != null) {
            serverChannel.close();
        }
        if (group != null) {
            group.shutdownGracefully();
        }
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpProxyConnectException(io.netty.handler.proxy.HttpProxyHandler.HttpProxyConnectException) LocalAddress(io.netty.channel.local.LocalAddress) LocalChannel(io.netty.channel.local.LocalChannel) InetSocketAddress(java.net.InetSocketAddress) LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Channel(io.netty.channel.Channel) AtomicReference(java.util.concurrent.atomic.AtomicReference) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) HttpResponseEncoder(io.netty.handler.codec.http.HttpResponseEncoder) EventLoopGroup(io.netty.channel.EventLoopGroup) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) LocalServerChannel(io.netty.channel.local.LocalServerChannel) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test)

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