1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.example.securechat;
17
18 import io.netty.bootstrap.Bootstrap;
19 import io.netty.channel.Channel;
20 import io.netty.channel.ChannelFuture;
21 import io.netty.channel.EventLoopGroup;
22 import io.netty.channel.nio.NioEventLoopGroup;
23 import io.netty.channel.socket.nio.NioSocketChannel;
24 import io.netty.example.telnet.TelnetClient;
25 import io.netty.handler.ssl.SslContext;
26 import io.netty.handler.ssl.SslContextBuilder;
27 import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
28
29 import java.io.BufferedReader;
30 import java.io.InputStreamReader;
31
32
33
34
35 public final class SecureChatClient {
36
37 static final String HOST = System.getProperty("host", "127.0.0.1");
38 static final int PORT = Integer.parseInt(System.getProperty("port", "8992"));
39
40 public static void main(String[] args) throws Exception {
41
42 final SslContext sslCtx = SslContextBuilder.forClient()
43 .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
44
45 EventLoopGroup group = new NioEventLoopGroup();
46 try {
47 Bootstrap b = new Bootstrap();
48 b.group(group)
49 .channel(NioSocketChannel.class)
50 .handler(new SecureChatClientInitializer(sslCtx));
51
52
53 Channel ch = b.connect(HOST, PORT).sync().channel();
54
55
56 ChannelFuture lastWriteFuture = null;
57 BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
58 for (;;) {
59 String line = in.readLine();
60 if (line == null) {
61 break;
62 }
63
64
65 lastWriteFuture = ch.writeAndFlush(line + "\r\n");
66
67
68
69 if ("bye".equals(line.toLowerCase())) {
70 ch.closeFuture().sync();
71 break;
72 }
73 }
74
75
76 if (lastWriteFuture != null) {
77 lastWriteFuture.sync();
78 }
79 } finally {
80
81 group.shutdownGracefully();
82 }
83 }
84 }