1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package io.netty.testsuite_jpms.main;
18
19 import io.netty.buffer.Unpooled;
20 import io.netty.channel.ChannelFuture;
21 import io.netty.channel.ChannelFutureListener;
22 import io.netty.channel.ChannelHandlerContext;
23 import io.netty.channel.SimpleChannelInboundHandler;
24 import io.netty.handler.codec.http.HttpObject;
25 import io.netty.handler.codec.http.HttpRequest;
26 import io.netty.handler.codec.http.HttpUtil;
27 import io.netty.handler.codec.http.FullHttpResponse;
28 import io.netty.handler.codec.http.DefaultFullHttpResponse;
29
30 import java.nio.charset.StandardCharsets;
31
32 import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION;
33 import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE;
34 import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;
35 import static io.netty.handler.codec.http.HttpHeaderValues.KEEP_ALIVE;
36 import static io.netty.handler.codec.http.HttpHeaderValues.CLOSE;
37 import static io.netty.handler.codec.http.HttpHeaderValues.TEXT_PLAIN;
38 import static io.netty.handler.codec.http.HttpResponseStatus.OK;
39
40 public class HttpHelloWorldServerHandler extends SimpleChannelInboundHandler<HttpObject> {
41
42 @Override
43 public void channelReadComplete(ChannelHandlerContext ctx) {
44 ctx.flush();
45 }
46
47 @Override
48 public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) {
49 if (msg instanceof HttpRequest) {
50 HttpRequest req = (HttpRequest) msg;
51
52 String hello = HttpHelloWorldServer.content(ctx);
53
54 boolean keepAlive = HttpUtil.isKeepAlive(req);
55 FullHttpResponse response = new DefaultFullHttpResponse(
56 req.protocolVersion(), OK,
57 Unpooled.copiedBuffer(hello, StandardCharsets.UTF_8));
58 response.headers()
59 .set(CONTENT_TYPE, TEXT_PLAIN)
60 .setInt(CONTENT_LENGTH, response.content().readableBytes());
61
62 if (keepAlive) {
63 if (!req.protocolVersion().isKeepAliveDefault()) {
64 response.headers().set(CONNECTION, KEEP_ALIVE);
65 }
66 } else {
67
68 response.headers().set(CONNECTION, CLOSE);
69 }
70
71 ChannelFuture f = ctx.write(response);
72
73 if (!keepAlive) {
74 f.addListener(ChannelFutureListener.CLOSE);
75 }
76 }
77 }
78
79 @Override
80 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
81 cause.printStackTrace();
82 ctx.close();
83 }
84 }