1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty5.testsuite.svm;
17
18 import io.netty5.channel.ChannelFutureListeners;
19 import io.netty5.channel.ChannelHandlerContext;
20 import io.netty5.channel.SimpleChannelInboundHandler;
21 import io.netty5.handler.codec.http.DefaultFullHttpResponse;
22 import io.netty5.handler.codec.http.FullHttpResponse;
23 import io.netty5.handler.codec.http.HttpObject;
24 import io.netty5.handler.codec.http.HttpRequest;
25 import io.netty5.handler.codec.http.HttpUtil;
26 import io.netty5.util.AsciiString;
27
28 import static io.netty5.handler.codec.http.HttpHeaderNames.CONNECTION;
29 import static io.netty5.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;
30 import static io.netty5.handler.codec.http.HttpHeaderNames.CONTENT_TYPE;
31 import static io.netty5.handler.codec.http.HttpResponseStatus.OK;
32 import static io.netty5.handler.codec.http.HttpVersion.HTTP_1_1;
33
34 public class HttpNativeServerHandler extends SimpleChannelInboundHandler<HttpObject> {
35 private static final byte[] CONTENT = { 'H', 'e', 'l', 'l', 'o', ' ', 'N', 'a', 't', 'i', 'v', 'e' };
36
37 private static final AsciiString KEEP_ALIVE = AsciiString.cached("keep-alive");
38
39 @Override
40 public void channelReadComplete(ChannelHandlerContext ctx) {
41 ctx.flush();
42 }
43
44 @Override
45 public void messageReceived(ChannelHandlerContext ctx, HttpObject msg) {
46 if (msg instanceof HttpRequest) {
47 HttpRequest req = (HttpRequest) msg;
48
49 boolean keepAlive = HttpUtil.isKeepAlive(req);
50 FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK,
51 ctx.bufferAllocator().allocate(CONTENT.length).writeBytes(CONTENT));
52 response.headers().set(CONTENT_TYPE, "text/plain");
53 response.headers().setInt(CONTENT_LENGTH, response.payload().readableBytes());
54
55 if (!keepAlive) {
56 ctx.write(response).addListener(ctx, ChannelFutureListeners.CLOSE);
57 } else {
58 response.headers().set(CONNECTION, KEEP_ALIVE);
59 ctx.write(response);
60 }
61 }
62 }
63
64 @Override
65 public void channelExceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
66 cause.printStackTrace();
67 ctx.close();
68 }
69 }