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();
}
}
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);
}
}
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);
}
}
}
});
}
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();
}
}
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();
}
Aggregations