1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package examples.unix;
19
20 import java.io.BufferedReader;
21 import java.io.IOException;
22 import java.io.InputStreamReader;
23 import java.io.InterruptedIOException;
24 import java.io.OutputStreamWriter;
25 import java.io.PrintWriter;
26 import java.net.InetAddress;
27 import java.net.SocketException;
28
29 import org.apache.commons.net.echo.EchoTCPClient;
30 import org.apache.commons.net.echo.EchoUDPClient;
31
32
33
34
35
36
37
38
39
40
41
42
43 public final class echo
44 {
45
46 public static final void echoTCP(String host) throws IOException
47 {
48 EchoTCPClient client = new EchoTCPClient();
49 BufferedReader input, echoInput;
50 PrintWriter echoOutput;
51 String line;
52
53
54 client.setDefaultTimeout(60000);
55 client.connect(host);
56 System.out.println("Connected to " + host + ".");
57 input = new BufferedReader(new InputStreamReader(System.in));
58 echoOutput =
59 new PrintWriter(new OutputStreamWriter(client.getOutputStream()), true);
60 echoInput =
61 new BufferedReader(new InputStreamReader(client.getInputStream()));
62
63 while ((line = input.readLine()) != null)
64 {
65 echoOutput.println(line);
66 System.out.println(echoInput.readLine());
67 }
68
69 client.disconnect();
70 }
71
72 public static final void echoUDP(String host) throws IOException
73 {
74 int length, count;
75 byte[] data;
76 String line;
77 BufferedReader input;
78 InetAddress address;
79 EchoUDPClient client;
80
81 input = new BufferedReader(new InputStreamReader(System.in));
82 address = InetAddress.getByName(host);
83 client = new EchoUDPClient();
84
85 client.open();
86
87 client.setSoTimeout(5000);
88 System.out.println("Ready to echo to " + host + ".");
89
90
91
92 while ((line = input.readLine()) != null)
93 {
94 data = line.getBytes();
95 client.send(data, address);
96 count = 0;
97 do
98 {
99 try
100 {
101 length = client.receive(data);
102 }
103
104
105
106
107 catch (SocketException e)
108 {
109
110 System.err.println(
111 "SocketException: Timed out and dropped packet");
112 break;
113 }
114 catch (InterruptedIOException e)
115 {
116
117 System.err.println(
118 "InterruptedIOException: Timed out and dropped packet");
119 break;
120 }
121 System.out.print(new String(data, 0, length));
122 count += length;
123 }
124 while (count < data.length);
125
126 System.out.println();
127 }
128
129 client.close();
130 }
131
132
133 public static void main(String[] args)
134 {
135
136 if (args.length == 1)
137 {
138 try
139 {
140 echoTCP(args[0]);
141 }
142 catch (IOException e)
143 {
144 e.printStackTrace();
145 System.exit(1);
146 }
147 }
148 else if (args.length == 2 && args[0].equals("-udp"))
149 {
150 try
151 {
152 echoUDP(args[1]);
153 }
154 catch (IOException e)
155 {
156 e.printStackTrace();
157 System.exit(1);
158 }
159 }
160 else
161 {
162 System.err.println("Usage: echo [-udp] <hostname>");
163 System.exit(1);
164 }
165
166 }
167
168 }
169