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 @Sharable
38 public class HelloWorldHttp2Handler extends ChannelDuplexHandler {
39
40 static final ByteBuf RESPONSE_BYTES = unreleasableBuffer(
41 copiedBuffer("Hello World", CharsetUtil.UTF_8)).asReadOnly();
42
43 @Override
44 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
45 super.exceptionCaught(ctx, cause);
46 cause.printStackTrace();
47 ctx.close();
48 }
49
50 @Override
51 public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
52 if (msg instanceof Http2HeadersFrame) {
53 onHeadersRead(ctx, (Http2HeadersFrame) msg);
54 } else if (msg instanceof Http2DataFrame) {
55 onDataRead(ctx, (Http2DataFrame) msg);
56 } else {
57 super.channelRead(ctx, msg);
58 }
59 }
60
61 @Override
62 public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
63 ctx.flush();
64 }
65
66
67
68
69 private static void onDataRead(ChannelHandlerContext ctx, Http2DataFrame data) throws Exception {
70 if (data.isEndStream()) {
71 sendResponse(ctx, data.content());
72 } else {
73
74 data.release();
75 }
76 }
77
78
79
80
81 private static void onHeadersRead(ChannelHandlerContext ctx, Http2HeadersFrame headers)
82 throws Exception {
83 if (headers.isEndStream()) {
84 ByteBuf content = ctx.alloc().buffer();
85 content.writeBytes(RESPONSE_BYTES.duplicate());
86 ByteBufUtil.writeAscii(content, " - via HTTP/2");
87 sendResponse(ctx, content);
88 }
89 }
90
91
92
93
94 private static void sendResponse(ChannelHandlerContext ctx, ByteBuf payload) {
95
96 Http2Headers headers = new DefaultHttp2Headers().status(OK.codeAsText());
97 ctx.write(new DefaultHttp2HeadersFrame(headers));
98 ctx.write(new DefaultHttp2DataFrame(payload, true));
99 }
100 }