1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.example.spdy.server;
17
18 import io.netty.buffer.ByteBuf;
19 import io.netty.buffer.Unpooled;
20 import io.netty.channel.ChannelFutureListener;
21 import io.netty.channel.ChannelHandlerContext;
22 import io.netty.channel.SimpleChannelInboundHandler;
23 import io.netty.handler.codec.http.DefaultFullHttpResponse;
24 import io.netty.handler.codec.http.FullHttpResponse;
25 import io.netty.handler.codec.http.HttpRequest;
26 import io.netty.util.CharsetUtil;
27
28 import java.util.Date;
29
30 import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION;
31 import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;
32 import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE;
33 import static io.netty.handler.codec.http.HttpHeaderValues.CLOSE;
34 import static io.netty.handler.codec.http.HttpHeaderValues.KEEP_ALIVE;
35 import static io.netty.handler.codec.http.HttpResponseStatus.CONTINUE;
36 import static io.netty.handler.codec.http.HttpResponseStatus.OK;
37 import static io.netty.handler.codec.http.HttpVersion.HTTP_1_0;
38 import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
39 import static io.netty.handler.codec.http.HttpUtil.is100ContinueExpected;
40 import static io.netty.handler.codec.http.HttpUtil.isKeepAlive;
41
42
43
44
45 public class SpdyServerHandler extends SimpleChannelInboundHandler<Object> {
46
47 @Override
48 public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
49 if (msg instanceof HttpRequest) {
50 HttpRequest req = (HttpRequest) msg;
51
52 if (is100ContinueExpected(req)) {
53 ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE, Unpooled.EMPTY_BUFFER));
54 }
55 boolean keepAlive = isKeepAlive(req);
56
57 ByteBuf content = Unpooled.copiedBuffer("Hello World " + new Date(), CharsetUtil.UTF_8);
58
59 FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
60 response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
61 response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());
62
63 if (keepAlive) {
64 if (req.protocolVersion().equals(HTTP_1_0)) {
65 response.headers().set(CONNECTION, KEEP_ALIVE);
66 }
67 ctx.write(response);
68 } else {
69
70 response.headers().set(CONNECTION, CLOSE);
71 ctx.write(response).addListener(ChannelFutureListener.CLOSE);
72 }
73 }
74 }
75
76 @Override
77 public void channelReadComplete(ChannelHandlerContext ctx) {
78 ctx.flush();
79 }
80
81 @Override
82 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
83 cause.printStackTrace();
84 ctx.close();
85 }
86 }