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