1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package io.netty.example.http2.tiles;
18
19 import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION;
20 import static io.netty.handler.codec.http.HttpHeaderValues.CLOSE;
21 import static io.netty.handler.codec.http.HttpHeaderValues.KEEP_ALIVE;
22 import static io.netty.handler.codec.http.HttpUtil.isKeepAlive;
23 import static io.netty.handler.codec.http.HttpResponseStatus.CONTINUE;
24 import static io.netty.handler.codec.http.HttpVersion.HTTP_1_0;
25 import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
26
27 import io.netty.buffer.Unpooled;
28 import io.netty.channel.ChannelFutureListener;
29 import io.netty.channel.ChannelHandlerContext;
30 import io.netty.handler.codec.http.DefaultFullHttpResponse;
31 import io.netty.handler.codec.http.FullHttpRequest;
32 import io.netty.handler.codec.http.FullHttpResponse;
33 import io.netty.handler.codec.http.HttpUtil;
34
35 import java.util.concurrent.TimeUnit;
36
37
38
39
40 public final class Http1RequestHandler extends Http2RequestHandler {
41
42 @Override
43 protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
44 if (HttpUtil.is100ContinueExpected(request)) {
45 ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE, Unpooled.EMPTY_BUFFER));
46 }
47 super.channelRead0(ctx, request);
48 }
49
50 @Override
51 protected void sendResponse(final ChannelHandlerContext ctx, String streamId, int latency,
52 final FullHttpResponse response, final FullHttpRequest request) {
53 HttpUtil.setContentLength(response, response.content().readableBytes());
54 ctx.executor().schedule(new Runnable() {
55 @Override
56 public void run() {
57 if (isKeepAlive(request)) {
58 if (request.protocolVersion().equals(HTTP_1_0)) {
59 response.headers().set(CONNECTION, KEEP_ALIVE);
60 }
61 ctx.writeAndFlush(response);
62 } else {
63
64 response.headers().set(CONNECTION, CLOSE);
65 ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
66 }
67 }
68 }, latency, TimeUnit.MILLISECONDS);
69 }
70 }