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