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