1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.example.http.helloworld;
17
18 import io.netty.buffer.Unpooled;
19 import io.netty.channel.ChannelFutureListener;
20 import io.netty.channel.ChannelHandlerContext;
21 import io.netty.channel.ChannelInboundHandlerAdapter;
22 import io.netty.handler.codec.http.DefaultFullHttpResponse;
23 import io.netty.handler.codec.http.FullHttpResponse;
24 import io.netty.handler.codec.http.HttpHeaders;
25 import io.netty.handler.codec.http.HttpRequest;
26
27 import static io.netty.handler.codec.http.HttpHeaders.Names.*;
28 import static io.netty.handler.codec.http.HttpHeaders.Values;
29 import static io.netty.handler.codec.http.HttpResponseStatus.*;
30 import static io.netty.handler.codec.http.HttpVersion.*;
31
32 public class HttpHelloWorldServerHandler extends ChannelInboundHandlerAdapter {
33 private static final byte[] CONTENT = { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd' };
34
35 @Override
36 public void channelReadComplete(ChannelHandlerContext ctx) {
37 ctx.flush();
38 }
39
40 @Override
41 public void channelRead(ChannelHandlerContext ctx, Object msg) {
42 if (msg instanceof HttpRequest) {
43 HttpRequest req = (HttpRequest) msg;
44
45 if (HttpHeaders.is100ContinueExpected(req)) {
46 ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
47 }
48 boolean keepAlive = HttpHeaders.isKeepAlive(req);
49 FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT));
50 response.headers().set(CONTENT_TYPE, "text/plain");
51 response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
52
53 if (!keepAlive) {
54 ctx.write(response).addListener(ChannelFutureListener.CLOSE);
55 } else {
56 response.headers().set(CONNECTION, Values.KEEP_ALIVE);
57 ctx.write(response);
58 }
59 }
60 }
61
62 @Override
63 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
64 cause.printStackTrace();
65 ctx.close();
66 }
67 }