1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.example.echo;
17
18 import io.netty.bootstrap.Bootstrap;
19 import io.netty.channel.ChannelFuture;
20 import io.netty.channel.ChannelInitializer;
21 import io.netty.channel.ChannelOption;
22 import io.netty.channel.ChannelPipeline;
23 import io.netty.channel.EventLoopGroup;
24 import io.netty.channel.nio.NioEventLoopGroup;
25 import io.netty.channel.socket.SocketChannel;
26 import io.netty.channel.socket.nio.NioSocketChannel;
27 import io.netty.handler.ssl.SslContext;
28 import io.netty.handler.ssl.SslContextBuilder;
29 import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
30
31
32
33
34
35
36
37 public final class EchoClient {
38
39 static final boolean SSL = System.getProperty("ssl") != null;
40 static final String HOST = System.getProperty("host", "127.0.0.1");
41 static final int PORT = Integer.parseInt(System.getProperty("port", "8007"));
42 static final int SIZE = Integer.parseInt(System.getProperty("size", "256"));
43
44 public static void main(String[] args) throws Exception {
45
46 final SslContext sslCtx;
47 if (SSL) {
48 sslCtx = SslContextBuilder.forClient()
49 .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
50 } else {
51 sslCtx = null;
52 }
53
54
55 EventLoopGroup group = new NioEventLoopGroup();
56 try {
57 Bootstrap b = new Bootstrap();
58 b.group(group)
59 .channel(NioSocketChannel.class)
60 .option(ChannelOption.TCP_NODELAY, true)
61 .handler(new ChannelInitializer<SocketChannel>() {
62 @Override
63 public void initChannel(SocketChannel ch) throws Exception {
64 ChannelPipeline p = ch.pipeline();
65 if (sslCtx != null) {
66 p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
67 }
68
69 p.addLast(new EchoClientHandler());
70 }
71 });
72
73
74 ChannelFuture f = b.connect(HOST, PORT).sync();
75
76
77 f.channel().closeFuture().sync();
78 } finally {
79
80 group.shutdownGracefully();
81 }
82 }
83 }