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.channel.ChannelHandlerContext;
19 import io.netty.channel.ChannelPipeline;
20 import io.netty.handler.codec.http.HttpObjectAggregator;
21 import io.netty.handler.codec.http.HttpServerCodec;
22 import io.netty.handler.codec.spdy.SpdyFrameCodec;
23 import io.netty.handler.codec.spdy.SpdyHttpDecoder;
24 import io.netty.handler.codec.spdy.SpdyHttpEncoder;
25 import io.netty.handler.codec.spdy.SpdyHttpResponseStreamIdHandler;
26 import io.netty.handler.codec.spdy.SpdySessionHandler;
27 import io.netty.handler.codec.spdy.SpdyVersion;
28 import io.netty.handler.ssl.ApplicationProtocolNames;
29 import io.netty.handler.ssl.ApplicationProtocolNegotiationHandler;
30
31
32
33
34
35 public class SpdyOrHttpHandler extends ApplicationProtocolNegotiationHandler {
36
37 private static final int MAX_CONTENT_LENGTH = 1024 * 100;
38
39 protected SpdyOrHttpHandler() {
40 super(ApplicationProtocolNames.HTTP_1_1);
41 }
42
43 @Override
44 protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception {
45 if (ApplicationProtocolNames.SPDY_3_1.equals(protocol)) {
46 configureSpdy(ctx, SpdyVersion.SPDY_3_1);
47 return;
48 }
49
50 if (ApplicationProtocolNames.HTTP_1_1.equals(protocol)) {
51 configureHttp1(ctx);
52 return;
53 }
54
55 throw new IllegalStateException("unknown protocol: " + protocol);
56 }
57
58 private static void configureSpdy(ChannelHandlerContext ctx, SpdyVersion version) throws Exception {
59 ChannelPipeline p = ctx.pipeline();
60 p.addLast(new SpdyFrameCodec(version));
61 p.addLast(new SpdySessionHandler(version, true));
62 p.addLast(new SpdyHttpEncoder(version));
63 p.addLast(new SpdyHttpDecoder(version, MAX_CONTENT_LENGTH));
64 p.addLast(new SpdyHttpResponseStreamIdHandler());
65 p.addLast(new SpdyServerHandler());
66 }
67
68 private static void configureHttp1(ChannelHandlerContext ctx) throws Exception {
69 ChannelPipeline p = ctx.pipeline();
70 p.addLast(new HttpServerCodec());
71 p.addLast(new HttpObjectAggregator(MAX_CONTENT_LENGTH));
72 p.addLast(new SpdyServerHandler());
73 }
74 }