1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jboss.netty.example.securechat;
17
18 import java.io.BufferedReader;
19 import java.io.InputStreamReader;
20 import java.net.InetSocketAddress;
21 import java.util.concurrent.Executors;
22
23 import org.jboss.netty.bootstrap.ClientBootstrap;
24 import org.jboss.netty.channel.Channel;
25 import org.jboss.netty.channel.ChannelFuture;
26 import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
27 import org.jboss.netty.example.telnet.TelnetClient;
28
29
30
31
32
33
34
35
36
37
38 public class SecureChatClient {
39
40 public static void main(String[] args) throws Exception {
41
42 if (args.length != 2) {
43 System.err.println(
44 "Usage: " + SecureChatClient.class.getSimpleName() +
45 " <host> <port>");
46 return;
47 }
48
49
50 String host = args[0];
51 int port = Integer.parseInt(args[1]);
52
53
54 ClientBootstrap bootstrap = new ClientBootstrap(
55 new NioClientSocketChannelFactory(
56 Executors.newCachedThreadPool(),
57 Executors.newCachedThreadPool()));
58
59
60 bootstrap.setPipelineFactory(new SecureChatClientPipelineFactory());
61
62
63 ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
64
65
66 Channel channel = future.awaitUninterruptibly().getChannel();
67 if (!future.isSuccess()) {
68 future.getCause().printStackTrace();
69 bootstrap.releaseExternalResources();
70 return;
71 }
72
73
74 ChannelFuture lastWriteFuture = null;
75 BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
76 for (;;) {
77 String line = in.readLine();
78 if (line == null) {
79 break;
80 }
81
82
83 lastWriteFuture = channel.write(line + "\r\n");
84
85
86
87 if (line.toLowerCase().equals("bye")) {
88 channel.getCloseFuture().awaitUninterruptibly();
89 break;
90 }
91 }
92
93
94 if (lastWriteFuture != null) {
95 lastWriteFuture.awaitUninterruptibly();
96 }
97
98
99
100 channel.close().awaitUninterruptibly();
101
102
103 bootstrap.releaseExternalResources();
104 }
105 }