On 13 September 2014 20:58, Anjib Mulepati <[email protected]> wrote:
> Hi All,
What version of NET are you using?
Java? OS?
> I couldn't understand why this program doesn't terminate if I send command?
What do you mean by not terminating?
Does it print "Disconnected" ?
Or does it hang somewhere previously, if so where?
> If I don't send the command it does terminate. I am trying to understand the
> way to issue sequence of command in telnet server.
>
> public class TelnetSample {
> private TelnetClient telnet = new TelnetClient();
> private InputStream in;
> private PrintStream out;
> private char prompt = '.';
>
> public TelnetSample( String server, String user, String password ) {
> try {
> // Connect to the specified server
> telnet.connect( server, 23 );
>
> // Get input and output stream references
> in = telnet.getInputStream();
> out = new PrintStream( telnet.getOutputStream() );
>
> // Advance to a prompt
> readUntil( prompt + " " );
> }
> catch( Exception e ) {
> e.printStackTrace();
> }
> }
>
> public String readUntil( String pattern ) {
> try {
> char lastChar = pattern.charAt( pattern.length() - 1 );
> StringBuffer sb = new StringBuffer();
> char ch = ( char )in.read();
What happens if read reaches EOF?
> while( true ) {
> System.out.print( ch );
> sb.append( ch );
> if( ch == lastChar ) {
> if( sb.toString().endsWith( pattern ) ) {
> return sb.toString();
> }
> }
> ch = ( char )in.read();
Ditto
> }
> }
> catch( Exception e ) {
> e.printStackTrace();
> }
> return null;
> }
>
> public void write( String value ) {
> try {
> out.println( value );
> out.flush();
> System.out.println( value );
> }
> catch( Exception e ) {
> e.printStackTrace();
> }
> }
>
> public String sendCommand( String command ) {
> try {
> write( command );
> return readUntil( prompt + " " );
> }
> catch( Exception e ) {
> e.printStackTrace();
> }
> return null;
> }
>
> public void disconnect() {
> try {
> telnet.disconnect();
> }
> catch( Exception e ) {
> e.printStackTrace();
> }
> }
>
> public static void main( String[] args ) {
> try {
> TelnetSample telnet = new TelnetSample( "telehack.com",
> "username",
> "password" );
> telnet.sendCommand( "date" );
> telnet.disconnect();
> System.out.println("Disconnected");
> }
> catch( Exception e ) {
> e.printStackTrace();
> }
> }
>
> }
>
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: [email protected]
> For additional commands, e-mail: [email protected]
>
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]