Search in sources :

Example 96 with ServerBootstrap

use of org.apache.flink.shaded.netty4.io.netty.bootstrap.ServerBootstrap in project apiRecord by tobecoder2015.

the class NettyHttpProxyServer method start.

public void start(int port) {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    // ChannelInboundHandlerAdapter
    try {
        init();
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).childHandler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                ch.pipeline().addLast("httpCodec", new HttpServerCodec());
                ch.pipeline().addLast(new ReadTimeoutHandler(10));
                ch.pipeline().addLast(new WriteTimeoutHandler(10));
                ch.pipeline().addLast("serverHandle", new HttpProxyServerHandle(proxyInterceptFactory.build()));
            }
        });
        ChannelFuture f = b.bind(port).sync();
        f.channel().closeFuture().sync();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
Also used : NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) WriteTimeoutHandler(io.netty.handler.timeout.WriteTimeoutHandler) ReadTimeoutHandler(io.netty.handler.timeout.ReadTimeoutHandler) HttpProxyServerHandle(com.wing.apirecord.core.handler.HttpProxyServerHandle) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap)

Example 97 with ServerBootstrap

use of org.apache.flink.shaded.netty4.io.netty.bootstrap.ServerBootstrap in project jocean-http by isdom.

the class HttpServerDemo method main.

public static void main(final String[] args) throws Exception {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    final // SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
    SslContext sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    // create for LocalChannel
    @SuppressWarnings("resource") final HttpServerBuilder server = new DefaultHttpServerBuilder(new AbstractBootstrapCreator(new DefaultEventLoopGroup(1), new DefaultEventLoopGroup()) {

        @Override
        protected void initializeBootstrap(final ServerBootstrap bootstrap) {
            bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
            bootstrap.channel(LocalServerChannel.class);
        }
    }, Feature.ENABLE_LOGGING, new Feature.ENABLE_SSL(sslCtx));
    @SuppressWarnings("unused") final Subscription subscription = server.defineServer(new LocalAddress("test")).subscribe(new Action1<HttpTrade>() {

        @Override
        public void call(final HttpTrade trade) {
            trade.outbound(trade.inbound().compose(RxNettys.message2fullreq(trade)).map(DisposableWrapperUtil.<FullHttpRequest>unwrap()).map(new Func1<FullHttpRequest, HttpObject>() {

                @Override
                public HttpObject call(final FullHttpRequest fullreq) {
                    try {
                        final FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(Nettys.dumpByteBufAsBytes(fullreq.content())));
                        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
                        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
                        return response;
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            }));
        }
    });
    @SuppressWarnings("resource") final DefaultHttpClient client = new DefaultHttpClient(new TestChannelCreator(), Feature.ENABLE_LOGGING, new Feature.ENABLE_SSL(SslContextBuilder.forClient().build()));
    while (true) {
        final ByteBuf content = Unpooled.buffer(0);
        content.writeBytes("test content".getBytes("UTF-8"));
        final DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/", content);
        HttpUtil.setContentLength(request, content.readableBytes());
        /* // TODO using initiator
            final Iterator<HttpObject> itr =
                client.defineInteraction(
                new LocalAddress("test"), 
                Observable.just(request))
                .map(RxNettys.<HttpObject>retainer())
                .toBlocking().toIterable().iterator();
            
            final byte[] bytes = RxNettys.httpObjectsAsBytes(itr);
            LOG.info("recv Response: {}", new String(bytes, "UTF-8"));
            */
        Thread.sleep(1000);
    }
}
Also used : SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) HttpServerBuilder(org.jocean.http.server.HttpServerBuilder) ByteBuf(io.netty.buffer.ByteBuf) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) Feature(org.jocean.http.Feature) DefaultHttpClient(org.jocean.http.client.impl.DefaultHttpClient) HttpTrade(org.jocean.http.server.HttpServerBuilder.HttpTrade) LocalServerChannel(io.netty.channel.local.LocalServerChannel) HttpObject(io.netty.handler.codec.http.HttpObject) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) Subscription(rx.Subscription) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) LocalAddress(io.netty.channel.local.LocalAddress) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) TestChannelCreator(org.jocean.http.client.impl.TestChannelCreator)

Example 98 with ServerBootstrap

use of org.apache.flink.shaded.netty4.io.netty.bootstrap.ServerBootstrap in project jocean-http by isdom.

the class DefaultHttpServerBuilder method defineServer.

public Observable<? extends HttpTrade> defineServer(final SocketAddress localAddress, final Func0<Feature[]> featuresBuilder, final Feature... features) {
    return Observable.unsafeCreate(new Observable.OnSubscribe<HttpTrade>() {

        @Override
        public void call(final Subscriber<? super HttpTrade> subscriber) {
            if (!subscriber.isUnsubscribed()) {
                final ServerBootstrap bootstrap = _creator.newBootstrap();
                final List<Channel> awaitChannels = new CopyOnWriteArrayList<>();
                bootstrap.childHandler(new Initializer() {

                    @Override
                    protected void initChannel(final Channel channel) throws Exception {
                        channel.config().setAutoRead(false);
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("dump inbound channel({})'s config: \n{}", channel, Nettys.dumpChannelConfig(channel.config()));
                        }
                        if (_inboundRecvBufSize > 0) {
                            if (LOG.isDebugEnabled()) {
                                LOG.debug("channel({})'s default SO_RCVBUF is {} bytes, and will be reset to {} bytes", channel, channel.config().getOption(ChannelOption.SO_RCVBUF), _inboundRecvBufSize);
                            }
                            channel.config().setOption(ChannelOption.SO_RCVBUF, _inboundRecvBufSize);
                        }
                        final Feature[] actualFeatures = JOArrays.addFirst(Feature[].class, featuresOf(featuresBuilder), features);
                        final Feature[] applyFeatures = (null != actualFeatures && actualFeatures.length > 0) ? actualFeatures : _defaultFeatures;
                        for (Feature feature : applyFeatures) {
                            if (feature instanceof FeatureOverChannelHandler) {
                                ((FeatureOverChannelHandler) feature).call(_APPLY_BUILDER, channel.pipeline());
                                if (LOG.isDebugEnabled()) {
                                    LOG.debug("initChannel with feature:{}", feature);
                                }
                            }
                        }
                        Nettys.applyHandler(channel.pipeline(), HttpHandlers.HTTPSERVER);
                        awaitInboundRequest(channel, subscriber, awaitChannels);
                    }
                });
                final ChannelFuture future = bootstrap.bind(localAddress);
                try {
                    future.sync();
                    subscriber.add(RxNettys.subscriptionForCloseChannel(future.channel()));
                    subscriber.add(Subscriptions.create(new Action0() {

                        @Override
                        public void call() {
                            while (!awaitChannels.isEmpty()) {
                                try {
                                    awaitChannels.remove(0).close();
                                } catch (Exception e) {
                                    LOG.warn("exception when remove all awaitChannels, detail: {}", ExceptionUtils.exception2detail(e));
                                }
                            }
                        }
                    }));
                    if (null != features) {
                        final ServerChannelAware serverChannelAware = serverChannelAwareOf(features);
                        if (null != serverChannelAware) {
                            serverChannelAware.setServerChannel((ServerChannel) future.channel());
                        }
                    }
                } catch (Exception e) {
                    subscriber.onError(e);
                }
            }
        }
    });
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) Action0(rx.functions.Action0) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) ServerChannel(io.netty.channel.ServerChannel) Channel(io.netty.channel.Channel) ServerChannelAware(org.jocean.http.util.Nettys.ServerChannelAware) ServerChannel(io.netty.channel.ServerChannel) Feature(org.jocean.http.Feature) Observable(rx.Observable) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) IOException(java.io.IOException) ChannelInitializer(io.netty.channel.ChannelInitializer) FeatureOverChannelHandler(org.jocean.http.Feature.FeatureOverChannelHandler) ArrayList(java.util.ArrayList) List(java.util.List) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList)

Example 99 with ServerBootstrap

use of org.apache.flink.shaded.netty4.io.netty.bootstrap.ServerBootstrap in project jocean-http by isdom.

the class Nettys4Test method createLocalConnection4Http.

public static Pair<Channel, Channel> createLocalConnection4Http(final String addr) throws Exception {
    final BlockingQueue<Channel> serverChannels = new ArrayBlockingQueue<Channel>(1);
    final Bootstrap clientbootstrap = new Bootstrap().group(Nettys4Test.EVENTLOOP4CLIENT).channel(LocalChannel.class).handler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(final Channel ch) throws Exception {
            Nettys.applyHandler(ch.pipeline(), HttpHandlers.LOGGING);
            Nettys.applyHandler(ch.pipeline(), HttpHandlers.HTTPCLIENT);
        }
    }).remoteAddress(new LocalAddress(addr));
    final Channel acceptorChannel = new ServerBootstrap().group(EVENTLOOP4BOSS, EVENTLOOP4SERVER).channel(LocalServerChannel.class).childHandler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(final Channel ch) throws Exception {
            Nettys.applyHandler(ch.pipeline(), HttpHandlers.LOGGING);
            Nettys.applyHandler(ch.pipeline(), HttpHandlers.HTTPSERVER);
            serverChannels.offer(ch);
        }
    }).localAddress(new LocalAddress(addr)).bind().sync().channel();
    try {
        final Channel client = clientbootstrap.connect().sync().channel();
        final Channel server = serverChannels.take();
        return Pair.of(client, server);
    } finally {
        acceptorChannel.close().sync();
    }
}
Also used : LocalAddress(io.netty.channel.local.LocalAddress) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) Channel(io.netty.channel.Channel) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) ServerBootstrap(io.netty.bootstrap.ServerBootstrap)

Example 100 with ServerBootstrap

use of org.apache.flink.shaded.netty4.io.netty.bootstrap.ServerBootstrap in project ratpack by ratpack.

the class DefaultRatpackServer method buildChannel.

protected Channel buildChannel(final ServerConfig serverConfig, final ChannelHandler handlerAdapter) throws InterruptedException {
    SslContext sslContext = serverConfig.getNettySslContext();
    this.useSsl = sslContext != null;
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverConfig.getConnectTimeoutMillis().ifPresent(i -> {
        serverBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, i);
        serverBootstrap.childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, i);
    });
    serverConfig.getMaxMessagesPerRead().ifPresent(i -> {
        FixedRecvByteBufAllocator allocator = new FixedRecvByteBufAllocator(i);
        serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, allocator);
        serverBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, allocator);
    });
    serverConfig.getReceiveBufferSize().ifPresent(i -> {
        serverBootstrap.option(ChannelOption.SO_RCVBUF, i);
        serverBootstrap.childOption(ChannelOption.SO_RCVBUF, i);
    });
    serverConfig.getWriteSpinCount().ifPresent(i -> {
        serverBootstrap.option(ChannelOption.WRITE_SPIN_COUNT, i);
        serverBootstrap.childOption(ChannelOption.WRITE_SPIN_COUNT, i);
    });
    serverConfig.getConnectQueueSize().ifPresent(i -> serverBootstrap.option(ChannelOption.SO_BACKLOG, i));
    return serverBootstrap.group(execController.getEventLoopGroup()).channel(ChannelImplDetector.getServerSocketChannelImpl()).option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT).childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT).childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            new ConnectionIdleTimeout(pipeline, serverConfig.getIdleTimeout());
            if (sslContext != null) {
                SSLEngine sslEngine = sslContext.newEngine(PooledByteBufAllocator.DEFAULT);
                pipeline.addLast("ssl", new SslHandler(sslEngine));
            }
            pipeline.addLast("decoder", new HttpRequestDecoder(serverConfig.getMaxInitialLineLength(), serverConfig.getMaxHeaderSize(), serverConfig.getMaxChunkSize(), false));
            pipeline.addLast("encoder", new HttpResponseEncoder());
            pipeline.addLast("deflater", new IgnorableHttpContentCompressor());
            pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
            pipeline.addLast("adapter", handlerAdapter);
            ch.config().setAutoRead(false);
        }
    }).bind(buildSocketAddress(serverConfig)).sync().channel();
}
Also used : SocketChannel(io.netty.channel.socket.SocketChannel) SSLEngine(javax.net.ssl.SSLEngine) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) SslHandler(io.netty.handler.ssl.SslHandler) HttpResponseEncoder(io.netty.handler.codec.http.HttpResponseEncoder) ChunkedWriteHandler(io.netty.handler.stream.ChunkedWriteHandler) HttpRequestDecoder(io.netty.handler.codec.http.HttpRequestDecoder) ConnectionIdleTimeout(ratpack.http.internal.ConnectionIdleTimeout) SslContext(io.netty.handler.ssl.SslContext)

Aggregations

ServerBootstrap (io.netty.bootstrap.ServerBootstrap)448 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)246 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)239 Channel (io.netty.channel.Channel)187 ChannelFuture (io.netty.channel.ChannelFuture)183 EventLoopGroup (io.netty.channel.EventLoopGroup)168 Bootstrap (io.netty.bootstrap.Bootstrap)134 SocketChannel (io.netty.channel.socket.SocketChannel)126 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)115 InetSocketAddress (java.net.InetSocketAddress)113 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)98 ChannelPipeline (io.netty.channel.ChannelPipeline)88 LoggingHandler (io.netty.handler.logging.LoggingHandler)82 LocalServerChannel (io.netty.channel.local.LocalServerChannel)76 LocalChannel (io.netty.channel.local.LocalChannel)73 CountDownLatch (java.util.concurrent.CountDownLatch)66 Test (org.junit.jupiter.api.Test)66 LocalAddress (io.netty.channel.local.LocalAddress)61 SelfSignedCertificate (io.netty.handler.ssl.util.SelfSignedCertificate)60 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)57