1+ package com .mycmd .commands ;
2+
3+ import com .mycmd .ShellContext ;
4+
5+ import java .io .*;
6+ import java .net .Socket ;
7+
8+ /**
9+ * TelnetCommand - simple TCP client for interactive sessions.
10+ * Usage: telnet <host> [port]
11+ *
12+ * Notes:
13+ * - This is a minimal implementation (no Telnet option negotiation).
14+ * - It will take over stdin while connected; type 'exit' to return to the shell.
15+ */
16+ public class TelnetCommand implements Command {
17+
18+ @ Override
19+ public void execute (String [] args , ShellContext context ) throws Exception {
20+ if (args .length < 1 ) {
21+ System .out .println ("Usage: telnet <host> [port]" );
22+ return ;
23+ }
24+
25+ String host = args [0 ];
26+ int port = 23 ;
27+ if (args .length >= 2 ) {
28+ try {
29+ port = Integer .parseInt (args [1 ]);
30+ } catch (NumberFormatException e ) {
31+ System .out .println ("Invalid port: " + args [1 ]);
32+ return ;
33+ }
34+ }
35+
36+ try (Socket socket = new Socket (host , port )) {
37+ socket .setSoTimeout (0 ); // blocking reads
38+ System .out .println ("Connected to " + host + ":" + port + " (type 'exit' to quit)" );
39+
40+ // Reader thread: prints remote data to stdout
41+ Thread reader = new Thread (() -> {
42+ try (InputStream in = socket .getInputStream ();
43+ InputStreamReader isr = new InputStreamReader (in );
44+ BufferedReader br = new BufferedReader (isr )) {
45+
46+ char [] buffer = new char [2048 ];
47+ int read ;
48+ while ((read = br .read (buffer )) != -1 ) {
49+ System .out .print (new String (buffer , 0 , read ));
50+ System .out .flush ();
51+ }
52+ } catch (IOException ignored ) {
53+ // socket closed or stream ended
54+ }
55+ }, "telnet-reader" );
56+ reader .setDaemon (true );
57+ reader .start ();
58+
59+ // Writer loop: read stdin and send to remote
60+ try (OutputStream out = socket .getOutputStream ();
61+ OutputStreamWriter osw = new OutputStreamWriter (out );
62+ BufferedWriter bw = new BufferedWriter (osw );
63+ BufferedReader stdin = new BufferedReader (new InputStreamReader (System .in ))) {
64+
65+ String line ;
66+ while ((line = stdin .readLine ()) != null ) {
67+ if ("exit" .equalsIgnoreCase (line .trim ())) break ;
68+ bw .write (line );
69+ bw .write ("\r \n " ); // typical telnet line ending
70+ bw .flush ();
71+ }
72+ } catch (IOException ignored ) {
73+ // stdin/socket error, will disconnect
74+ }
75+
76+ // ensure socket closes to stop reader
77+ try { socket .close (); } catch (IOException ignored ) {}
78+ System .out .println ("\n Disconnected." );
79+ } catch (IOException e ) {
80+ System .out .println ("Connection failed: " + e .getMessage ());
81+ }
82+ }
83+ }
0 commit comments