View Javadoc
1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  package org.apache.hc.core5.reactive.examples;
28  
29  import java.net.InetSocketAddress;
30  import java.util.concurrent.Future;
31  import java.util.concurrent.TimeUnit;
32  
33  import org.apache.hc.core5.http.ContentType;
34  import org.apache.hc.core5.http.HeaderElements;
35  import org.apache.hc.core5.http.HttpConnection;
36  import org.apache.hc.core5.http.HttpHeaders;
37  import org.apache.hc.core5.http.HttpRequest;
38  import org.apache.hc.core5.http.HttpResponse;
39  import org.apache.hc.core5.http.URIScheme;
40  import org.apache.hc.core5.http.impl.BasicEntityDetails;
41  import org.apache.hc.core5.http.impl.Http1StreamListener;
42  import org.apache.hc.core5.http.impl.bootstrap.AsyncServerBootstrap;
43  import org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer;
44  import org.apache.hc.core5.http.message.BasicHeader;
45  import org.apache.hc.core5.http.message.BasicHttpResponse;
46  import org.apache.hc.core5.http.message.RequestLine;
47  import org.apache.hc.core5.http.message.StatusLine;
48  import org.apache.hc.core5.io.CloseMode;
49  import org.apache.hc.core5.reactive.ReactiveServerExchangeHandler;
50  import org.apache.hc.core5.reactor.IOReactorConfig;
51  import org.apache.hc.core5.reactor.ListenerEndpoint;
52  import org.apache.hc.core5.util.TimeValue;
53  
54  /**
55   * Example of full-duplex HTTP/1.1 message exchanges using reactive streaming. This demo server works out-of-the-box
56   * with {@link ReactiveFullDuplexClientExample}; it can also be invoked interactively using telnet.
57   */
58  public class ReactiveFullDuplexServerExample {
59      public static void main(final String[] args) throws Exception {
60          int port = 8080;
61          if (args.length >= 1) {
62              port = Integer.parseInt(args[0]);
63          }
64  
65          final IOReactorConfig config = IOReactorConfig.custom()
66              .setSoTimeout(15, TimeUnit.SECONDS)
67              .setTcpNoDelay(true)
68              .build();
69  
70          final HttpAsyncServer server = AsyncServerBootstrap.bootstrap()
71              .setIOReactorConfig(config)
72              .setStreamListener(new Http1StreamListener() {
73                  @Override
74                  public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
75                      System.out.println(connection.getRemoteAddress() + " " + new RequestLine(request));
76  
77                  }
78  
79                  @Override
80                  public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
81                      System.out.println(connection.getRemoteAddress() + " " + new StatusLine(response));
82                  }
83  
84                  @Override
85                  public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
86                      if (keepAlive) {
87                          System.out.println(connection.getRemoteAddress() + " exchange completed (connection kept alive)");
88                      } else {
89                          System.out.println(connection.getRemoteAddress() + " exchange completed (connection closed)");
90                      }
91                  }
92  
93              })
94              .register("/echo", () -> new ReactiveServerExchangeHandler((request, entityDetails, responseChannel, context, requestBody, responseBodyFuture) -> {
95                  if (new BasicHeader(HttpHeaders.EXPECT, HeaderElements.CONTINUE).equals(request.getHeader(HttpHeaders.EXPECT))) {
96                      responseChannel.sendInformation(new BasicHttpResponse(100), context);
97                  }
98  
99                  responseChannel.sendResponse(
100                         new BasicHttpResponse(200),
101                         new BasicEntityDetails(-1, ContentType.APPLICATION_OCTET_STREAM),
102                         context);
103 
104                 // Simply using the request publisher as the response publisher will
105                 // cause the server to echo the request body.
106                 responseBodyFuture.execute(requestBody);
107             }))
108             .create();
109 
110         Runtime.getRuntime().addShutdownHook(new Thread(() -> {
111             System.out.println("HTTP server shutting down");
112             server.close(CloseMode.GRACEFUL);
113         }));
114 
115         server.start();
116         final Future<ListenerEndpoint> future = server.listen(new InetSocketAddress(port), URIScheme.HTTP);
117         final ListenerEndpoint listenerEndpoint = future.get();
118         System.out.print("Listening on " + listenerEndpoint.getAddress());
119         server.awaitShutdown(TimeValue.ofDays(Long.MAX_VALUE));
120     }
121 }