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