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.http.examples;
28  
29  import java.io.IOException;
30  import java.net.InetSocketAddress;
31  import java.net.SocketException;
32  import java.nio.ByteBuffer;
33  import java.util.List;
34  import java.util.concurrent.Future;
35  import java.util.concurrent.TimeUnit;
36  
37  import org.apache.hc.core5.http.EntityDetails;
38  import org.apache.hc.core5.http.Header;
39  import org.apache.hc.core5.http.HttpConnection;
40  import org.apache.hc.core5.http.HttpException;
41  import org.apache.hc.core5.http.HttpRequest;
42  import org.apache.hc.core5.http.HttpResponse;
43  import org.apache.hc.core5.http.HttpStatus;
44  import org.apache.hc.core5.http.URIScheme;
45  import org.apache.hc.core5.http.impl.Http1StreamListener;
46  import org.apache.hc.core5.http.impl.bootstrap.AsyncServerBootstrap;
47  import org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer;
48  import org.apache.hc.core5.http.message.BasicHttpResponse;
49  import org.apache.hc.core5.http.message.RequestLine;
50  import org.apache.hc.core5.http.message.StatusLine;
51  import org.apache.hc.core5.http.nio.AsyncServerExchangeHandler;
52  import org.apache.hc.core5.http.nio.CapacityChannel;
53  import org.apache.hc.core5.http.nio.DataStreamChannel;
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.reactor.IOReactorConfig;
58  import org.apache.hc.core5.reactor.ListenerEndpoint;
59  import org.apache.hc.core5.util.TimeValue;
60  
61  /**
62   * Example of full-duplex, streaming HTTP message exchanges with an asynchronous embedded HTTP/1.1 server.
63   */
64  public class AsyncFullDuplexServerExample {
65  
66      public static void main(final String[] args) throws Exception {
67          int port = 8080;
68          if (args.length >= 1) {
69              port = Integer.parseInt(args[0]);
70          }
71  
72          final IOReactorConfig config = IOReactorConfig.custom()
73                  .setSoTimeout(15, TimeUnit.SECONDS)
74                  .setTcpNoDelay(true)
75                  .build();
76  
77          final HttpAsyncServer server = AsyncServerBootstrap.bootstrap()
78                  .setIOReactorConfig(config)
79                  .setStreamListener(new Http1StreamListener() {
80  
81                      @Override
82                      public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
83                          System.out.println(connection.getRemoteAddress() + " " + new RequestLine(request));
84                      }
85  
86                      @Override
87                      public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
88                          System.out.println(connection.getRemoteAddress() + " " + new StatusLine(response));
89                      }
90  
91                      @Override
92                      public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
93                          if (keepAlive) {
94                              System.out.println(connection.getRemoteAddress() + " exchange completed (connection kept alive)");
95                          } else {
96                              System.out.println(connection.getRemoteAddress() + " exchange completed (connection closed)");
97                          }
98                      }
99  
100                 })
101                 .register("/echo", () -> new AsyncServerExchangeHandler() {
102 
103                     ByteBuffer buffer = ByteBuffer.allocate(2048);
104                     CapacityChannel inputCapacityChannel;
105                     DataStreamChannel outputDataChannel;
106                     boolean endStream;
107 
108                     private void ensureCapacity(final int chunk) {
109                         if (buffer.remaining() < chunk) {
110                             final ByteBuffer oldBuffer = buffer;
111                             oldBuffer.flip();
112                             buffer = ByteBuffer.allocate(oldBuffer.remaining() + (chunk > 2048 ? chunk : 2048));
113                             buffer.put(oldBuffer);
114                         }
115                     }
116 
117                     @Override
118                     public void handleRequest(
119                             final HttpRequest request,
120                             final EntityDetails entityDetails,
121                             final ResponseChannel responseChannel,
122                             final HttpContext context) throws HttpException, IOException {
123                         final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_OK);
124                         responseChannel.sendResponse(response, entityDetails, context);
125                     }
126 
127                     @Override
128                     public void consume(final ByteBuffer src) throws IOException {
129                         if (buffer.position() == 0) {
130                             if (outputDataChannel != null) {
131                                 outputDataChannel.write(src);
132                             }
133                         }
134                         if (src.hasRemaining()) {
135                             ensureCapacity(src.remaining());
136                             buffer.put(src);
137                             if (outputDataChannel != null) {
138                                 outputDataChannel.requestOutput();
139                             }
140                         }
141                     }
142 
143                     @Override
144                     public void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
145                         if (buffer.hasRemaining()) {
146                             capacityChannel.update(buffer.remaining());
147                             inputCapacityChannel = null;
148                         } else {
149                             inputCapacityChannel = capacityChannel;
150                         }
151                     }
152 
153                     @Override
154                     public void streamEnd(final List<? extends Header> trailers) throws IOException {
155                         endStream = true;
156                         if (buffer.position() == 0) {
157                             if (outputDataChannel != null) {
158                                 outputDataChannel.endStream();
159                             }
160                         } else {
161                             if (outputDataChannel != null) {
162                                 outputDataChannel.requestOutput();
163                             }
164                         }
165                     }
166 
167                     @Override
168                     public int available() {
169                         return buffer.position();
170                     }
171 
172                     @Override
173                     public void produce(final DataStreamChannel channel) throws IOException {
174                         outputDataChannel = channel;
175                         buffer.flip();
176                         if (buffer.hasRemaining()) {
177                             channel.write(buffer);
178                         }
179                         buffer.compact();
180                         if (buffer.position() == 0 && endStream) {
181                             channel.endStream();
182                         }
183                         final CapacityChannel capacityChannel = inputCapacityChannel;
184                         if (capacityChannel != null && buffer.hasRemaining()) {
185                             capacityChannel.update(buffer.remaining());
186                         }
187                     }
188 
189                     @Override
190                     public void failed(final Exception cause) {
191                         if (!(cause instanceof SocketException)) {
192                             cause.printStackTrace(System.out);
193                         }
194                     }
195 
196                     @Override
197                     public void releaseResources() {
198                     }
199 
200                 })
201                 .create();
202 
203         Runtime.getRuntime().addShutdownHook(new Thread(() -> {
204             System.out.println("HTTP server shutting down");
205             server.close(CloseMode.GRACEFUL);
206         }));
207 
208         server.start();
209         final Future<ListenerEndpoint> future = server.listen(new InetSocketAddress(port), URIScheme.HTTP);
210         final ListenerEndpoint listenerEndpoint = future.get();
211         System.out.print("Listening on " + listenerEndpoint.getAddress());
212         server.awaitShutdown(TimeValue.MAX_VALUE);
213     }
214 
215 }