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.HttpHeaders.Names.*;
31 import static io.netty.handler.codec.http.HttpHeaders.*;
32 import static io.netty.handler.codec.http.HttpResponseStatus.*;
33 import static io.netty.handler.codec.http.HttpVersion.*;
34
35
36
37
38 public class SpdyServerHandler extends SimpleChannelInboundHandler<Object> {
39
40 @Override
41 public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
42 if (msg instanceof HttpRequest) {
43 HttpRequest req = (HttpRequest) msg;
44
45 if (is100ContinueExpected(req)) {
46 ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
47 }
48 boolean keepAlive = isKeepAlive(req);
49
50 ByteBuf content = Unpooled.copiedBuffer("Hello World " + new Date(), CharsetUtil.UTF_8);
51
52 FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
53 response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
54 response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
55
56 if (!keepAlive) {
57 ctx.write(response).addListener(ChannelFutureListener.CLOSE);
58 } else {
59 response.headers().set(CONNECTION, Values.KEEP_ALIVE);
60 ctx.write(response);
61 }
62 }
63 }
64
65 @Override
66 public void channelReadComplete(ChannelHandlerContext ctx) {
67 ctx.flush();
68 }
69
70 @Override
71 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
72 cause.printStackTrace();
73 ctx.close();
74 }
75 }