1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.example.spdy.client;
17
18 import io.netty.bootstrap.Bootstrap;
19 import io.netty.buffer.Unpooled;
20 import io.netty.channel.Channel;
21 import io.netty.channel.ChannelOption;
22 import io.netty.channel.EventLoopGroup;
23 import io.netty.channel.nio.NioEventLoopGroup;
24 import io.netty.channel.socket.nio.NioSocketChannel;
25 import io.netty.handler.codec.http.DefaultFullHttpRequest;
26 import io.netty.handler.codec.http.HttpHeaderNames;
27 import io.netty.handler.codec.http.HttpHeaderValues;
28 import io.netty.handler.codec.http.HttpMethod;
29 import io.netty.handler.codec.http.HttpRequest;
30 import io.netty.handler.codec.http.HttpVersion;
31 import io.netty.handler.ssl.ApplicationProtocolConfig;
32 import io.netty.handler.ssl.ApplicationProtocolConfig.Protocol;
33 import io.netty.handler.ssl.ApplicationProtocolConfig.SelectedListenerFailureBehavior;
34 import io.netty.handler.ssl.ApplicationProtocolConfig.SelectorFailureBehavior;
35 import io.netty.handler.ssl.ApplicationProtocolNames;
36 import io.netty.handler.ssl.SslContext;
37 import io.netty.handler.ssl.SslContextBuilder;
38 import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53 public final class SpdyClient {
54
55 static final String HOST = System.getProperty("host", "127.0.0.1");
56 static final int PORT = Integer.parseInt(System.getProperty("port", "8443"));
57
58 public static void main(String[] args) throws Exception {
59
60 final SslContext sslCtx = SslContextBuilder.forClient()
61 .trustManager(InsecureTrustManagerFactory.INSTANCE)
62 .applicationProtocolConfig(new ApplicationProtocolConfig(
63 Protocol.NPN,
64
65 SelectorFailureBehavior.NO_ADVERTISE,
66
67 SelectedListenerFailureBehavior.ACCEPT,
68 ApplicationProtocolNames.SPDY_3_1,
69 ApplicationProtocolNames.HTTP_1_1))
70 .build();
71
72 HttpResponseClientHandler httpResponseHandler = new HttpResponseClientHandler();
73 EventLoopGroup workerGroup = new NioEventLoopGroup();
74
75 try {
76 Bootstrap b = new Bootstrap();
77 b.group(workerGroup);
78 b.channel(NioSocketChannel.class);
79 b.option(ChannelOption.SO_KEEPALIVE, true);
80 b.remoteAddress(HOST, PORT);
81 b.handler(new SpdyClientInitializer(sslCtx, httpResponseHandler));
82
83
84 Channel channel = b.connect().syncUninterruptibly().channel();
85 System.out.println("Connected to " + HOST + ':' + PORT);
86
87
88 HttpRequest request = new DefaultFullHttpRequest(
89 HttpVersion.HTTP_1_1, HttpMethod.GET, "", Unpooled.EMPTY_BUFFER);
90 request.headers().set(HttpHeaderNames.HOST, HOST);
91 request.headers().set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
92
93
94 channel.writeAndFlush(request).sync();
95
96
97 httpResponseHandler.queue().take().sync();
98 System.out.println("Finished SPDY HTTP GET");
99
100
101 channel.close().syncUninterruptibly();
102 } finally {
103 workerGroup.shutdownGracefully();
104 }
105 }
106 }