1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty5.example.http2.helloworld.frame.server;
17
18 import io.netty5.buffer.api.Buffer;
19 import io.netty5.channel.ChannelHandler;
20 import io.netty5.channel.ChannelHandlerContext;
21 import io.netty5.handler.codec.http2.DefaultHttp2DataFrame;
22 import io.netty5.handler.codec.http2.DefaultHttp2Headers;
23 import io.netty5.handler.codec.http2.DefaultHttp2HeadersFrame;
24 import io.netty5.handler.codec.http2.DefaultHttp2WindowUpdateFrame;
25 import io.netty5.handler.codec.http2.Http2DataFrame;
26 import io.netty5.handler.codec.http2.Http2FrameStream;
27 import io.netty5.handler.codec.http2.Http2Headers;
28 import io.netty5.handler.codec.http2.Http2HeadersFrame;
29
30 import java.nio.charset.StandardCharsets;
31
32 import static io.netty5.handler.codec.http.HttpResponseStatus.OK;
33
34
35
36
37
38
39 public class HelloWorldHttp2Handler implements ChannelHandler {
40
41 static final byte[] RESPONSE_BYTES = "Hello World".getBytes(StandardCharsets.UTF_8);
42
43 @Override
44 public boolean isSharable() {
45 return true;
46 }
47
48 @Override
49 public void channelExceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
50 ctx.fireChannelExceptionCaught(cause);
51 cause.printStackTrace();
52 ctx.close();
53 }
54
55 @Override
56 public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
57 if (msg instanceof Http2HeadersFrame) {
58 onHeadersRead(ctx, (Http2HeadersFrame) msg);
59 } else if (msg instanceof Http2DataFrame) {
60 onDataRead(ctx, (Http2DataFrame) msg);
61 } else {
62 ctx.fireChannelRead(msg);
63 }
64 }
65
66 @Override
67 public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
68 ctx.flush();
69 }
70
71
72
73
74 private static void onDataRead(ChannelHandlerContext ctx, Http2DataFrame data) throws Exception {
75 Http2FrameStream stream = data.stream();
76
77 if (data.isEndStream()) {
78 sendResponse(ctx, stream, data.content());
79 } else {
80
81 data.close();
82 }
83
84
85 ctx.write(new DefaultHttp2WindowUpdateFrame(data.initialFlowControlledBytes()).stream(stream));
86 }
87
88
89
90
91 private static void onHeadersRead(ChannelHandlerContext ctx, Http2HeadersFrame headers)
92 throws Exception {
93 if (headers.isEndStream()) {
94 Buffer content = ctx.bufferAllocator().copyOf(RESPONSE_BYTES);
95 content.writeCharSequence(" - via HTTP/2", StandardCharsets.US_ASCII);
96 sendResponse(ctx, headers.stream(), content);
97 }
98 }
99
100
101
102
103 private static void sendResponse(ChannelHandlerContext ctx, Http2FrameStream stream, Buffer payload) {
104
105 Http2Headers headers = new DefaultHttp2Headers().status(OK.codeAsText());
106 ctx.write(new DefaultHttp2HeadersFrame(headers).stream(stream));
107 ctx.write(new DefaultHttp2DataFrame(payload.send(), true).stream(stream));
108 }
109 }