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.io.IOException;
30  import java.net.InetSocketAddress;
31  import java.nio.ByteBuffer;
32  import java.util.concurrent.Future;
33  import java.util.concurrent.TimeUnit;
34  
35  import org.apache.hc.core5.function.Callback;
36  import org.apache.hc.core5.function.Supplier;
37  import org.apache.hc.core5.http.ContentType;
38  import org.apache.hc.core5.http.EntityDetails;
39  import org.apache.hc.core5.http.HeaderElements;
40  import org.apache.hc.core5.http.HttpConnection;
41  import org.apache.hc.core5.http.HttpException;
42  import org.apache.hc.core5.http.HttpHeaders;
43  import org.apache.hc.core5.http.HttpRequest;
44  import org.apache.hc.core5.http.HttpResponse;
45  import org.apache.hc.core5.http.impl.BasicEntityDetails;
46  import org.apache.hc.core5.http.impl.Http1StreamListener;
47  import org.apache.hc.core5.http.impl.bootstrap.AsyncServerBootstrap;
48  import org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer;
49  import org.apache.hc.core5.http.message.BasicHeader;
50  import org.apache.hc.core5.http.message.BasicHttpResponse;
51  import org.apache.hc.core5.http.message.RequestLine;
52  import org.apache.hc.core5.http.message.StatusLine;
53  import org.apache.hc.core5.http.nio.AsyncServerExchangeHandler;
54  import org.apache.hc.core5.http.nio.ResponseChannel;
55  import org.apache.hc.core5.http.protocol.HttpContext;
56  import org.apache.hc.core5.io.CloseMode;
57  import org.apache.hc.core5.reactive.ReactiveRequestProcessor;
58  import org.apache.hc.core5.reactive.ReactiveServerExchangeHandler;
59  import org.apache.hc.core5.reactor.IOReactorConfig;
60  import org.apache.hc.core5.reactor.ListenerEndpoint;
61  import org.apache.hc.core5.util.TimeValue;
62  import org.reactivestreams.Publisher;
63  
64  /**
65   * Example of full-duplex HTTP/1.1 message exchanges using reactive streaming. This demo server works out-of-the-box
66   * with {@link ReactiveFullDuplexClientExample}; it can also be invoked interactively using telnet.
67   */
68  public class ReactiveFullDuplexServerExample {
69      public static void main(final String[] args) throws Exception {
70          int port = 8080;
71          if (args.length >= 1) {
72              port = Integer.parseInt(args[0]);
73          }
74  
75          final IOReactorConfig config = IOReactorConfig.custom()
76              .setSoTimeout(15, TimeUnit.SECONDS)
77              .setTcpNoDelay(true)
78              .build();
79  
80          final HttpAsyncServer server = AsyncServerBootstrap.bootstrap()
81              .setIOReactorConfig(config)
82              .setStreamListener(new Http1StreamListener() {
83                  @Override
84                  public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
85                      System.out.println(connection.getRemoteAddress() + " " + new RequestLine(request));
86  
87                  }
88  
89                  @Override
90                  public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
91                      System.out.println(connection.getRemoteAddress() + " " + new StatusLine(response));
92                  }
93  
94                  @Override
95                  public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
96                      if (keepAlive) {
97                          System.out.println(connection.getRemoteAddress() + " exchange completed (connection kept alive)");
98                      } else {
99                          System.out.println(connection.getRemoteAddress() + " exchange completed (connection closed)");
100                     }
101                 }
102 
103             })
104             .register("/echo", new Supplier<AsyncServerExchangeHandler>() {
105                 @Override
106                 public AsyncServerExchangeHandler get() {
107                     return new ReactiveServerExchangeHandler(new ReactiveRequestProcessor() {
108                         @Override
109                         public void processRequest(
110                             final HttpRequest request,
111                             final EntityDetails entityDetails,
112                             final ResponseChannel responseChannel,
113                             final HttpContext context,
114                             final Publisher<ByteBuffer> requestBody,
115                             final Callback<Publisher<ByteBuffer>> responseBodyFuture
116                         ) throws HttpException, IOException {
117                             if (new BasicHeader(HttpHeaders.EXPECT, HeaderElements.CONTINUE).equals(request.getHeader(HttpHeaders.EXPECT))) {
118                                 responseChannel.sendInformation(new BasicHttpResponse(100), context);
119                             }
120 
121                             responseChannel.sendResponse(
122                                 new BasicHttpResponse(200),
123                                 new BasicEntityDetails(-1, ContentType.APPLICATION_OCTET_STREAM),
124                                 context);
125 
126                             // Simply using the request publisher as the response publisher will
127                             // cause the server to echo the request body.
128                             responseBodyFuture.execute(requestBody);
129                         }
130                     });
131                 }
132             })
133             .create();
134 
135         Runtime.getRuntime().addShutdownHook(new Thread() {
136             @Override
137             public void run() {
138                 System.out.println("HTTP server shutting down");
139                 server.close(CloseMode.GRACEFUL);
140             }
141         });
142 
143         server.start();
144         final Future<ListenerEndpoint> future = server.listen(new InetSocketAddress(port));
145         final ListenerEndpoint listenerEndpoint = future.get();
146         System.out.print("Listening on " + listenerEndpoint.getAddress());
147         server.awaitShutdown(TimeValue.ofDays(Long.MAX_VALUE));
148     }
149 }