use of org.apache.hc.core5.http2.config.H2Config in project httpcomponents-core by apache.
the class H2FullDuplexClientExample method main.
public static void main(final String[] args) throws Exception {
final IOReactorConfig ioReactorConfig = IOReactorConfig.custom().setSoTimeout(5, TimeUnit.SECONDS).build();
// Create and start requester
final H2Config h2Config = H2Config.custom().setPushEnabled(false).setMaxConcurrentStreams(100).build();
final HttpAsyncRequester requester = H2RequesterBootstrap.bootstrap().setIOReactorConfig(ioReactorConfig).setH2Config(h2Config).setVersionPolicy(HttpVersionPolicy.FORCE_HTTP_2).setStreamListener(new H2StreamListener() {
@Override
public void onHeaderInput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
for (int i = 0; i < headers.size(); i++) {
System.out.println(connection.getRemoteAddress() + " (" + streamId + ") << " + headers.get(i));
}
}
@Override
public void onHeaderOutput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
for (int i = 0; i < headers.size(); i++) {
System.out.println(connection.getRemoteAddress() + " (" + streamId + ") >> " + headers.get(i));
}
}
@Override
public void onFrameInput(final HttpConnection connection, final int streamId, final RawFrame frame) {
}
@Override
public void onFrameOutput(final HttpConnection connection, final int streamId, final RawFrame frame) {
}
@Override
public void onInputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
}
@Override
public void onOutputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
}
}).create();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("HTTP requester shutting down");
requester.close(CloseMode.GRACEFUL);
}));
requester.start();
final URI requestUri = new URI("http://nghttp2.org/httpbin/post");
final AsyncRequestProducer requestProducer = AsyncRequestBuilder.post(requestUri).setEntity("stuff").build();
final BasicResponseConsumer<String> responseConsumer = new BasicResponseConsumer<>(new StringAsyncEntityConsumer());
final CountDownLatch latch = new CountDownLatch(1);
requester.execute(new AsyncClientExchangeHandler() {
@Override
public void releaseResources() {
requestProducer.releaseResources();
responseConsumer.releaseResources();
latch.countDown();
}
@Override
public void cancel() {
System.out.println(requestUri + " cancelled");
}
@Override
public void failed(final Exception cause) {
System.out.println(requestUri + "->" + cause);
}
@Override
public void produceRequest(final RequestChannel channel, final HttpContext httpContext) throws HttpException, IOException {
requestProducer.sendRequest(channel, httpContext);
}
@Override
public int available() {
return requestProducer.available();
}
@Override
public void produce(final DataStreamChannel channel) throws IOException {
requestProducer.produce(channel);
}
@Override
public void consumeInformation(final HttpResponse response, final HttpContext httpContext) throws HttpException, IOException {
System.out.println(requestUri + "->" + response.getCode());
}
@Override
public void consumeResponse(final HttpResponse response, final EntityDetails entityDetails, final HttpContext httpContext) throws HttpException, IOException {
System.out.println(requestUri + "->" + response.getCode());
responseConsumer.consumeResponse(response, entityDetails, httpContext, null);
}
@Override
public void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
responseConsumer.updateCapacity(capacityChannel);
}
@Override
public void consume(final ByteBuffer src) throws IOException {
responseConsumer.consume(src);
}
@Override
public void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
responseConsumer.streamEnd(trailers);
}
}, Timeout.ofSeconds(30), HttpCoreContext.create());
latch.await();
System.out.println("Shutting down I/O reactor");
requester.initiateShutdown();
}
use of org.apache.hc.core5.http2.config.H2Config in project httpcomponents-core by apache.
the class H2FullDuplexServerExample method main.
public static void main(final String[] args) throws Exception {
int port = 8080;
if (args.length >= 1) {
port = Integer.parseInt(args[0]);
}
final IOReactorConfig config = IOReactorConfig.custom().setSoTimeout(15, TimeUnit.SECONDS).setTcpNoDelay(true).build();
final H2Config h2Config = H2Config.custom().setPushEnabled(true).setMaxConcurrentStreams(100).build();
final HttpAsyncServer server = H2ServerBootstrap.bootstrap().setIOReactorConfig(config).setH2Config(h2Config).setVersionPolicy(HttpVersionPolicy.FORCE_HTTP_2).setStreamListener(new H2StreamListener() {
@Override
public void onHeaderInput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
for (int i = 0; i < headers.size(); i++) {
System.out.println(connection.getRemoteAddress() + " (" + streamId + ") << " + headers.get(i));
}
}
@Override
public void onHeaderOutput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
for (int i = 0; i < headers.size(); i++) {
System.out.println(connection.getRemoteAddress() + " (" + streamId + ") >> " + headers.get(i));
}
}
@Override
public void onFrameInput(final HttpConnection connection, final int streamId, final RawFrame frame) {
}
@Override
public void onFrameOutput(final HttpConnection connection, final int streamId, final RawFrame frame) {
}
@Override
public void onInputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
}
@Override
public void onOutputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
}
}).register("/echo", () -> new AsyncServerExchangeHandler() {
ByteBuffer buffer = ByteBuffer.allocate(2048);
CapacityChannel inputCapacityChannel;
DataStreamChannel outputDataChannel;
boolean endStream;
private void ensureCapacity(final int chunk) {
if (buffer.remaining() < chunk) {
final ByteBuffer oldBuffer = buffer;
oldBuffer.flip();
buffer = ByteBuffer.allocate(oldBuffer.remaining() + (chunk > 2048 ? chunk : 2048));
buffer.put(oldBuffer);
}
}
@Override
public void handleRequest(final HttpRequest request, final EntityDetails entityDetails, final ResponseChannel responseChannel, final HttpContext context) throws HttpException, IOException {
final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_OK);
responseChannel.sendResponse(response, entityDetails, context);
}
@Override
public void consume(final ByteBuffer src) throws IOException {
if (buffer.position() == 0) {
if (outputDataChannel != null) {
outputDataChannel.write(src);
}
}
if (src.hasRemaining()) {
ensureCapacity(src.remaining());
buffer.put(src);
if (outputDataChannel != null) {
outputDataChannel.requestOutput();
}
}
}
@Override
public void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
if (buffer.hasRemaining()) {
capacityChannel.update(buffer.remaining());
inputCapacityChannel = null;
} else {
inputCapacityChannel = capacityChannel;
}
}
@Override
public void streamEnd(final List<? extends Header> trailers) throws IOException {
endStream = true;
if (buffer.position() == 0) {
if (outputDataChannel != null) {
outputDataChannel.endStream();
}
} else {
if (outputDataChannel != null) {
outputDataChannel.requestOutput();
}
}
}
@Override
public int available() {
return buffer.position();
}
@Override
public void produce(final DataStreamChannel channel) throws IOException {
outputDataChannel = channel;
buffer.flip();
if (buffer.hasRemaining()) {
channel.write(buffer);
}
buffer.compact();
if (buffer.position() == 0 && endStream) {
channel.endStream();
}
final CapacityChannel capacityChannel = inputCapacityChannel;
if (capacityChannel != null && buffer.hasRemaining()) {
capacityChannel.update(buffer.remaining());
}
}
@Override
public void failed(final Exception cause) {
if (!(cause instanceof SocketException)) {
cause.printStackTrace(System.out);
}
}
@Override
public void releaseResources() {
}
}).create();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("HTTP server shutting down");
server.close(CloseMode.GRACEFUL);
}));
server.start();
final Future<ListenerEndpoint> future = server.listen(new InetSocketAddress(port), URIScheme.HTTP);
final ListenerEndpoint listenerEndpoint = future.get();
System.out.print("Listening on " + listenerEndpoint.getAddress());
server.awaitShutdown(TimeValue.ofDays(Long.MAX_VALUE));
}
use of org.apache.hc.core5.http2.config.H2Config in project mercury by yellow013.
the class AsyncClientH2ServerPush method main.
public static void main(final String[] args) throws Exception {
final IOReactorConfig ioReactorConfig = IOReactorConfig.custom().setSoTimeout(Timeout.ofSeconds(5)).build();
final H2Config h2Config = H2Config.custom().setPushEnabled(true).build();
final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setIOReactorConfig(ioReactorConfig).setVersionPolicy(HttpVersionPolicy.FORCE_HTTP_2).setH2Config(h2Config).build();
client.start();
client.register("*", new Supplier<AsyncPushConsumer>() {
@Override
public AsyncPushConsumer get() {
return new AbstractBinPushConsumer() {
@Override
protected void start(final HttpRequest promise, final HttpResponse response, final ContentType contentType) throws HttpException, IOException {
System.out.println(promise.getPath() + " (push)->" + new StatusLine(response));
}
@Override
protected int capacityIncrement() {
return Integer.MAX_VALUE;
}
@Override
protected void data(final ByteBuffer data, final boolean endOfStream) throws IOException {
}
@Override
protected void completed() {
}
@Override
public void failed(final Exception cause) {
System.out.println("(push)->" + cause);
}
@Override
public void releaseResources() {
}
};
}
});
final BasicHttpRequest request = BasicRequestBuilder.get("https://nghttp2.org/httpbin/").build();
System.out.println("Executing request " + request);
final Future<Void> future = client.execute(new BasicRequestProducer(request, null), new AbstractCharResponseConsumer<Void>() {
@Override
protected void start(final HttpResponse response, final ContentType contentType) throws HttpException, IOException {
System.out.println(request + "->" + new StatusLine(response));
}
@Override
protected int capacityIncrement() {
return Integer.MAX_VALUE;
}
@Override
protected void data(final CharBuffer data, final boolean endOfStream) throws IOException {
}
@Override
protected Void buildResult() throws IOException {
return null;
}
@Override
public void failed(final Exception cause) {
System.out.println(request + "->" + cause);
}
@Override
public void releaseResources() {
}
}, null);
future.get();
System.out.println("Shutting down");
client.close(CloseMode.GRACEFUL);
}
use of org.apache.hc.core5.http2.config.H2Config in project httpcomponents-core by apache.
the class InternalClientProtocolNegotiationStarter method createHandler.
@Override
public IOEventHandler createHandler(final ProtocolIOSession ioSession, final Object attachment) {
if (sslContext != null) {
ioSession.startTls(sslContext, null, null, sslSessionInitializer, sslSessionVerifier, null);
}
final ClientHttp1StreamDuplexerFactory http1StreamHandlerFactory = new ClientHttp1StreamDuplexerFactory(httpProcessor != null ? httpProcessor : HttpProcessors.client(), http1Config, charCodingConfig, LoggingHttp1StreamListener.INSTANCE_CLIENT);
final ClientH2StreamMultiplexerFactory http2StreamHandlerFactory = new ClientH2StreamMultiplexerFactory(httpProcessor != null ? httpProcessor : H2Processors.client(), exchangeHandlerFactory, h2Config, charCodingConfig, LoggingH2StreamListener.INSTANCE);
ioSession.registerProtocol(ApplicationProtocol.HTTP_1_1.id, new ClientHttp1UpgradeHandler(http1StreamHandlerFactory));
ioSession.registerProtocol(ApplicationProtocol.HTTP_2.id, new ClientH2UpgradeHandler(http2StreamHandlerFactory));
switch(versionPolicy) {
case FORCE_HTTP_2:
return new ClientH2PrefaceHandler(ioSession, http2StreamHandlerFactory, false);
case FORCE_HTTP_1:
return new ClientHttp1IOEventHandler(http1StreamHandlerFactory.create(ioSession));
default:
return new HttpProtocolNegotiator(ioSession, null);
}
}
use of org.apache.hc.core5.http2.config.H2Config in project httpcomponents-core by apache.
the class InternalServerProtocolNegotiationStarter method createHandler.
@Override
public IOEventHandler createHandler(final ProtocolIOSession ioSession, final Object attachment) {
if (sslContext != null) {
ioSession.startTls(sslContext, null, null, sslSessionInitializer, sslSessionVerifier, null);
}
final ServerHttp1StreamDuplexerFactory http1StreamHandlerFactory = new ServerHttp1StreamDuplexerFactory(httpProcessor != null ? httpProcessor : HttpProcessors.server(), exchangeHandlerFactory, http1Config, charCodingConfig, LoggingHttp1StreamListener.INSTANCE_SERVER);
final ServerH2StreamMultiplexerFactory http2StreamHandlerFactory = new ServerH2StreamMultiplexerFactory(httpProcessor != null ? httpProcessor : H2Processors.server(), exchangeHandlerFactory, h2Config, charCodingConfig, LoggingH2StreamListener.INSTANCE);
ioSession.registerProtocol(ApplicationProtocol.HTTP_1_1.id, new ServerHttp1UpgradeHandler(http1StreamHandlerFactory));
ioSession.registerProtocol(ApplicationProtocol.HTTP_2.id, new ServerH2UpgradeHandler(http2StreamHandlerFactory));
switch(versionPolicy) {
case FORCE_HTTP_2:
return new ServerH2PrefaceHandler(ioSession, http2StreamHandlerFactory);
case FORCE_HTTP_1:
return new ServerHttp1IOEventHandler(http1StreamHandlerFactory.create(sslContext != null ? URIScheme.HTTPS.id : URIScheme.HTTP.id, ioSession));
default:
return new HttpProtocolNegotiator(ioSession, null);
}
}
Aggregations