View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.commons.net.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  import java.time.Duration;
29  
30  import org.apache.commons.net.echo.EchoTCPClient;
31  import org.apache.commons.net.echo.EchoUDPClient;
32  
33  /**
34   * This is an example program demonstrating how to use the EchoTCPClient and EchoUDPClient classes. This program connects to the default echo service port of a
35   * specified server, then reads lines from standard input, writing them to the echo server, and then printing the echo. The default is to use the TCP port. Use
36   * the -udp flag to use the UDP port.
37   * <p>
38   * Usage: echo [-udp] <hostname>
39   * </p>
40   */
41  public final class echo {
42  
43      public static void echoTCP(final String host) throws IOException {
44          final EchoTCPClient client = new EchoTCPClient();
45          String line;
46  
47          // We want to timeout if a response takes longer than 60 seconds
48          client.setDefaultTimeout(60000);
49          client.connect(host);
50          try {
51              System.out.println("Connected to " + host + ".");
52              final BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
53              try (PrintWriter echoOutput = new PrintWriter(new OutputStreamWriter(client.getOutputStream()), true);
54                      BufferedReader echoInput = new BufferedReader(new InputStreamReader(client.getInputStream()))) {
55                  while ((line = input.readLine()) != null) {
56                      echoOutput.println(line);
57                      System.out.println(echoInput.readLine());
58                  }
59              }
60              // Don't close System.in
61          } finally {
62              client.disconnect();
63          }
64      }
65  
66      public static void echoUDP(final String host) throws IOException {
67          int length, count;
68          byte[] data;
69          String line;
70          final BufferedReader input;
71          final InetAddress address;
72  
73          input = new BufferedReader(new InputStreamReader(System.in));
74          address = InetAddress.getByName(host);
75          try (EchoUDPClient client = new EchoUDPClient()) {
76  
77              client.open();
78              // If we don't receive an echo within 5 seconds, assume the packet is lost.
79              client.setSoTimeout(Duration.ofSeconds(5));
80              System.out.println("Ready to echo to " + host + ".");
81  
82              // Remember, there are no guarantees about the ordering of returned
83              // UDP packets, so there is a chance the output may be jumbled.
84              while ((line = input.readLine()) != null) {
85                  data = line.getBytes();
86                  client.send(data, address);
87                  count = 0;
88                  do {
89                      try {
90                          length = client.receive(data);
91                      }
92                      // Here we catch both SocketException and InterruptedIOException,
93                      // because even though the JDK 1.1 docs claim that
94                      // InterruptedIOException is thrown on a timeout, it seems
95                      // SocketException is also thrown.
96                      catch (final SocketException e) {
97                          // We timed out and assume the packet is lost.
98                          System.err.println("SocketException: Timed out and dropped packet");
99                          break;
100                     } catch (final InterruptedIOException e) {
101                         // We timed out and assume the packet is lost.
102                         System.err.println("InterruptedIOException: Timed out and dropped packet");
103                         break;
104                     }
105                     System.out.print(new String(data, 0, length));
106                     count += length;
107                 } while (count < data.length);
108 
109                 System.out.println();
110             }
111 
112         }
113     }
114 
115     public static void main(final String[] args) {
116 
117         if (args.length == 1) {
118             try {
119                 echoTCP(args[0]);
120             } catch (final IOException e) {
121                 e.printStackTrace();
122                 System.exit(1);
123             }
124         } else if (args.length == 2 && args[0].equals("-udp")) {
125             try {
126                 echoUDP(args[1]);
127             } catch (final IOException e) {
128                 e.printStackTrace();
129                 System.exit(1);
130             }
131         } else {
132             System.err.println("Usage: echo [-udp] <hostname>");
133             System.exit(1);
134         }
135 
136     }
137 
138 }