1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.example.http2.helloworld.server;
17
18 import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION;
19 import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;
20 import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE;
21 import static io.netty.handler.codec.http.HttpHeaderValues.CLOSE;
22 import static io.netty.handler.codec.http.HttpHeaderValues.KEEP_ALIVE;
23 import static io.netty.handler.codec.http.HttpResponseStatus.CONTINUE;
24 import static io.netty.handler.codec.http.HttpResponseStatus.OK;
25 import static io.netty.handler.codec.http.HttpVersion.HTTP_1_0;
26 import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
27 import static io.netty.util.internal.ObjectUtil.checkNotNull;
28
29 import io.netty.buffer.ByteBuf;
30 import io.netty.buffer.ByteBufUtil;
31 import io.netty.buffer.Unpooled;
32 import io.netty.channel.ChannelFutureListener;
33 import io.netty.channel.ChannelHandlerContext;
34 import io.netty.channel.SimpleChannelInboundHandler;
35 import io.netty.handler.codec.http.DefaultFullHttpResponse;
36 import io.netty.handler.codec.http.FullHttpRequest;
37 import io.netty.handler.codec.http.FullHttpResponse;
38 import io.netty.handler.codec.http.HttpUtil;
39
40
41
42
43 public class HelloWorldHttp1Handler extends SimpleChannelInboundHandler<FullHttpRequest> {
44 private final String establishApproach;
45
46 public HelloWorldHttp1Handler(String establishApproach) {
47 this.establishApproach = checkNotNull(establishApproach, "establishApproach");
48 }
49
50 @Override
51 public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
52 if (HttpUtil.is100ContinueExpected(req)) {
53 ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE, Unpooled.EMPTY_BUFFER));
54 }
55
56 ByteBuf content = ctx.alloc().buffer();
57 content.writeBytes(HelloWorldHttp2Handler.RESPONSE_BYTES.duplicate());
58 ByteBufUtil.writeAscii(content, " - via " + req.protocolVersion() + " (" + establishApproach + ")");
59
60 FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
61 response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
62 response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());
63
64 boolean keepAlive = HttpUtil.isKeepAlive(req);
65 if (keepAlive) {
66 if (req.protocolVersion().equals(HTTP_1_0)) {
67 response.headers().set(CONNECTION, KEEP_ALIVE);
68 }
69 ctx.write(response);
70 } else {
71
72 response.headers().set(CONNECTION, CLOSE);
73 ctx.write(response).addListener(ChannelFutureListener.CLOSE);
74 }
75 }
76
77 @Override
78 public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
79 ctx.flush();
80 }
81
82 @Override
83 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
84 cause.printStackTrace();
85 ctx.close();
86 }
87 }