1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.example.http2.helloworld.multiplex.server;
17
18 import static io.netty.buffer.Unpooled.copiedBuffer;
19 import static io.netty.buffer.Unpooled.unreleasableBuffer;
20 import static io.netty.handler.codec.http.HttpResponseStatus.OK;
21 import io.netty.buffer.ByteBuf;
22 import io.netty.buffer.ByteBufUtil;
23 import io.netty.channel.ChannelDuplexHandler;
24 import io.netty.channel.ChannelHandler.Sharable;
25 import io.netty.channel.ChannelHandlerContext;
26 import io.netty.handler.codec.http2.DefaultHttp2DataFrame;
27 import io.netty.handler.codec.http2.DefaultHttp2Headers;
28 import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame;
29 import io.netty.handler.codec.http2.Http2DataFrame;
30 import io.netty.handler.codec.http2.Http2Headers;
31 import io.netty.handler.codec.http2.Http2HeadersFrame;
32 import io.netty.util.CharsetUtil;
33
34
35
36
37
38
39
40 @Sharable
41 public class HelloWorldHttp2Handler extends ChannelDuplexHandler {
42
43 static final ByteBuf RESPONSE_BYTES = unreleasableBuffer(
44 copiedBuffer("Hello World", CharsetUtil.UTF_8)).asReadOnly();
45
46 @Override
47 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
48 super.exceptionCaught(ctx, cause);
49 cause.printStackTrace();
50 ctx.close();
51 }
52
53 @Override
54 public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
55 if (msg instanceof Http2HeadersFrame) {
56 onHeadersRead(ctx, (Http2HeadersFrame) msg);
57 } else if (msg instanceof Http2DataFrame) {
58 onDataRead(ctx, (Http2DataFrame) msg);
59 } else {
60 super.channelRead(ctx, msg);
61 }
62 }
63
64 @Override
65 public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
66 ctx.flush();
67 }
68
69
70
71
72 private static void onDataRead(ChannelHandlerContext ctx, Http2DataFrame data) throws Exception {
73 if (data.isEndStream()) {
74 sendResponse(ctx, data.content());
75 } else {
76
77 data.release();
78 }
79 }
80
81
82
83
84 private static void onHeadersRead(ChannelHandlerContext ctx, Http2HeadersFrame headers)
85 throws Exception {
86 if (headers.isEndStream()) {
87 ByteBuf content = ctx.alloc().buffer();
88 content.writeBytes(RESPONSE_BYTES.duplicate());
89 ByteBufUtil.writeAscii(content, " - via HTTP/2");
90 sendResponse(ctx, content);
91 }
92 }
93
94
95
96
97 private static void sendResponse(ChannelHandlerContext ctx, ByteBuf payload) {
98
99 Http2Headers headers = new DefaultHttp2Headers().status(OK.codeAsText());
100 ctx.write(new DefaultHttp2HeadersFrame(headers));
101 ctx.write(new DefaultHttp2DataFrame(payload, true));
102 }
103 }