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