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 examples;
19  
20  import java.io.InputStream;
21  import java.io.OutputStream;
22  import java.io.FileOutputStream;
23  import java.io.IOException;
24  import org.apache.commons.net.telnet.TelnetClient;
25  import org.apache.commons.net.telnet.TelnetNotificationHandler;
26  import org.apache.commons.net.telnet.SimpleOptionHandler;
27  import org.apache.commons.net.telnet.EchoOptionHandler;
28  import org.apache.commons.net.telnet.TerminalTypeOptionHandler;
29  import org.apache.commons.net.telnet.SuppressGAOptionHandler;
30  import org.apache.commons.net.telnet.InvalidTelnetOptionException;
31  import java.util.StringTokenizer;
32  
33  
34  /***
35   * This is a simple example of use of TelnetClient.
36   * An external option handler (SimpleTelnetOptionHandler) is used.
37   * Initial configuration requested by TelnetClient will be:
38   * WILL ECHO, WILL SUPPRESS-GA, DO SUPPRESS-GA.
39   * VT100 terminal type will be subnegotiated.
40   * <p>
41   * Also, use of the sendAYT(), getLocalOptionState(), getRemoteOptionState()
42   * is demonstrated.
43   * When connected, type AYT to send an AYT command to the server and see
44   * the result.
45   * Type OPT to see a report of the state of the first 25 options.
46   * <p>
47   * @author Bruno D'Avanzo
48   ***/
49  public class TelnetClientExample implements Runnable, TelnetNotificationHandler
50  {
51      static TelnetClient tc = null;
52  
53      /***
54       * Main for the TelnetClientExample.
55       ***/
56      public static void main(String[] args) throws IOException
57      {
58          FileOutputStream fout = null;
59  
60          if(args.length < 1)
61          {
62              System.err.println("Usage: TelnetClientExample1 <remote-ip> [<remote-port>]");
63              System.exit(1);
64          }
65  
66          String remoteip = args[0];
67  
68          int remoteport;
69  
70          if (args.length > 1)
71          {
72              remoteport = (new Integer(args[1])).intValue();
73          }
74          else
75          {
76              remoteport = 23;
77          }
78  
79          try
80          {
81              fout = new FileOutputStream ("spy.log", true);
82          }
83          catch (Exception e)
84          {
85              System.err.println(
86                  "Exception while opening the spy file: "
87                  + e.getMessage());
88          }
89  
90          tc = new TelnetClient();
91  
92          TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT100", false, false, true, false);
93          EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false);
94          SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true);
95  
96          try
97          {
98              tc.addOptionHandler(ttopt);
99              tc.addOptionHandler(echoopt);
100             tc.addOptionHandler(gaopt);
101         }
102         catch (InvalidTelnetOptionException e)
103         {
104             System.err.println("Error registering option handlers: " + e.getMessage());
105         }
106 
107         while (true)
108         {
109             boolean end_loop = false;
110             try
111             {
112                 tc.connect(remoteip, remoteport);
113 
114 
115                 Thread reader = new Thread (new TelnetClientExample());
116                 tc.registerNotifHandler(new TelnetClientExample());
117                 System.out.println("TelnetClientExample");
118                 System.out.println("Type AYT to send an AYT telnet command");
119                 System.out.println("Type OPT to print a report of status of options (0-24)");
120                 System.out.println("Type REGISTER to register a new SimpleOptionHandler");
121                 System.out.println("Type UNREGISTER to unregister an OptionHandler");
122                 System.out.println("Type SPY to register the spy (connect to port 3333 to spy)");
123                 System.out.println("Type UNSPY to stop spying the connection");
124 
125                 reader.start();
126                 OutputStream outstr = tc.getOutputStream();
127 
128                 byte[] buff = new byte[1024];
129                 int ret_read = 0;
130 
131                 do
132                 {
133                     try
134                     {
135                         ret_read = System.in.read(buff);
136                         if(ret_read > 0)
137                         {
138                             if((new String(buff, 0, ret_read)).startsWith("AYT"))
139                             {
140                                 try
141                                 {
142                                     System.out.println("Sending AYT");
143 
144                                     System.out.println("AYT response:" + tc.sendAYT(5000));
145                                 }
146                                 catch (Exception e)
147                                 {
148                                     System.err.println("Exception waiting AYT response: " + e.getMessage());
149                                 }
150                             }
151                             else if((new String(buff, 0, ret_read)).startsWith("OPT"))
152                             {
153                                  System.out.println("Status of options:");
154                                  for(int ii=0; ii<25; ii++)
155                                     System.out.println("Local Option " + ii + ":" + tc.getLocalOptionState(ii) + " Remote Option " + ii + ":" + tc.getRemoteOptionState(ii));
156                             }
157                             else if((new String(buff, 0, ret_read)).startsWith("REGISTER"))
158                             {
159                                 StringTokenizer st = new StringTokenizer(new String(buff));
160                                 try
161                                 {
162                                     st.nextToken();
163                                     int opcode = (new Integer(st.nextToken())).intValue();
164                                     boolean initlocal = (new Boolean(st.nextToken())).booleanValue();
165                                     boolean initremote = (new Boolean(st.nextToken())).booleanValue();
166                                     boolean acceptlocal = (new Boolean(st.nextToken())).booleanValue();
167                                     boolean acceptremote = (new Boolean(st.nextToken())).booleanValue();
168                                     SimpleOptionHandler opthand = new SimpleOptionHandler(opcode, initlocal, initremote,
169                                                                     acceptlocal, acceptremote);
170                                     tc.addOptionHandler(opthand);
171                                 }
172                                 catch (Exception e)
173                                 {
174                                     if(e instanceof InvalidTelnetOptionException)
175                                     {
176                                         System.err.println("Error registering option: " + e.getMessage());
177                                     }
178                                     else
179                                     {
180                                         System.err.println("Invalid REGISTER command.");
181                                         System.err.println("Use REGISTER optcode initlocal initremote acceptlocal acceptremote");
182                                         System.err.println("(optcode is an integer.)");
183                                         System.err.println("(initlocal, initremote, acceptlocal, acceptremote are boolean)");
184                                     }
185                                 }
186                             }
187                             else if((new String(buff, 0, ret_read)).startsWith("UNREGISTER"))
188                             {
189                                 StringTokenizer st = new StringTokenizer(new String(buff));
190                                 try
191                                 {
192                                     st.nextToken();
193                                     int opcode = (new Integer(st.nextToken())).intValue();
194                                     tc.deleteOptionHandler(opcode);
195                                 }
196                                 catch (Exception e)
197                                 {
198                                     if(e instanceof InvalidTelnetOptionException)
199                                     {
200                                         System.err.println("Error unregistering option: " + e.getMessage());
201                                     }
202                                     else
203                                     {
204                                         System.err.println("Invalid UNREGISTER command.");
205                                         System.err.println("Use UNREGISTER optcode");
206                                         System.err.println("(optcode is an integer)");
207                                     }
208                                 }
209                             }
210                             else if((new String(buff, 0, ret_read)).startsWith("SPY"))
211                             {
212                                 try
213                                 {
214                                     tc.registerSpyStream(fout);
215                                 }
216                                 catch (Exception e)
217                                 {
218                                     System.err.println("Error registering the spy");
219                                 }
220                             }
221                             else if((new String(buff, 0, ret_read)).startsWith("UNSPY"))
222                             {
223                                 tc.stopSpyStream();
224                             }
225                             else
226                             {
227                                 try
228                                 {
229                                         outstr.write(buff, 0 , ret_read);
230                                         outstr.flush();
231                                 }
232                                 catch (Exception e)
233                                 {
234                                         end_loop = true;
235                                 }
236                             }
237                         }
238                     }
239                     catch (Exception e)
240                     {
241                         System.err.println("Exception while reading keyboard:" + e.getMessage());
242                         end_loop = true;
243                     }
244                 }
245                 while((ret_read > 0) && (end_loop == false));
246 
247                 try
248                 {
249                     tc.disconnect();
250                 }
251                 catch (Exception e)
252                 {
253                           System.err.println("Exception while connecting:" + e.getMessage());
254                 }
255             }
256             catch (Exception e)
257             {
258                     System.err.println("Exception while connecting:" + e.getMessage());
259                     System.exit(1);
260             }
261         }
262     }
263 
264 
265     /***
266      * Callback method called when TelnetClient receives an option
267      * negotiation command.
268      * <p>
269      * @param negotiation_code - type of negotiation command received
270      * (RECEIVED_DO, RECEIVED_DONT, RECEIVED_WILL, RECEIVED_WONT)
271      * <p>
272      * @param option_code - code of the option negotiated
273      * <p>
274      ***/
275     public void receivedNegotiation(int negotiation_code, int option_code)
276     {
277         String command = null;
278         if(negotiation_code == TelnetNotificationHandler.RECEIVED_DO)
279         {
280             command = "DO";
281         }
282         else if(negotiation_code == TelnetNotificationHandler.RECEIVED_DONT)
283         {
284             command = "DONT";
285         }
286         else if(negotiation_code == TelnetNotificationHandler.RECEIVED_WILL)
287         {
288             command = "WILL";
289         }
290         else if(negotiation_code == TelnetNotificationHandler.RECEIVED_WONT)
291         {
292             command = "WONT";
293         }
294         System.out.println("Received " + command + " for option code " + option_code);
295    }
296 
297     /***
298      * Reader thread.
299      * Reads lines from the TelnetClient and echoes them
300      * on the screen.
301      ***/
302     public void run()
303     {
304         InputStream instr = tc.getInputStream();
305 
306         try
307         {
308             byte[] buff = new byte[1024];
309             int ret_read = 0;
310 
311             do
312             {
313                 ret_read = instr.read(buff);
314                 if(ret_read > 0)
315                 {
316                     System.out.print(new String(buff, 0, ret_read));
317                 }
318             }
319             while (ret_read >= 0);
320         }
321         catch (Exception e)
322         {
323             System.err.println("Exception while reading socket:" + e.getMessage());
324         }
325 
326         try
327         {
328             tc.disconnect();
329         }
330         catch (Exception e)
331         {
332             System.err.println("Exception while closing telnet:" + e.getMessage());
333         }
334     }
335 }
336