Foros del Web » Programación para mayores de 30 ;) » Java »

Telnet en java

Estas en el tema de Telnet en java en el foro de Java en Foros del Web. Que tal tengo hecho un cliente telnet en java, la conexion la realizo sin ningun inconveniente mi preblema es a la hora de ejecutar los ...
  #1 (permalink)  
Antiguo 30/05/2007, 14:22
 
Fecha de Ingreso: febrero-2006
Mensajes: 35
Antigüedad: 18 años, 3 meses
Puntos: 0
Telnet en java

Que tal tengo hecho un cliente telnet en java, la conexion la realizo sin ningun inconveniente mi preblema es a la hora de ejecutar los comandos ya que no se cuando es que deja de transmitir el servidor telnet devido a que me puede devolver varios paquetes de bytes, si alguien me puede dar una idea sera de gran ayuda.

public class TelnetInputStream extends InputStream
{
private static DataInputStream input;
private static DataOutputStream output;
private int width, height;
private String terminal;

// used for replies
private final byte[] reply = { IAC, (byte) 0, (byte) 0 };

public TelnetInputStream(InputStream inInput, OutputStream inOutput)
{
int inWidth=0;
int inHeight=0;
String inTermType=null;
System.out.println("Bien "+inInput+" "+inOutput);
input = (DataInputStream) inInput;
output = (DataOutputStream) inOutput;
width = inWidth;
height = inHeight;
terminal = inTermType;
if ( terminal == null ) terminal = "dumb";
try
{
String resultado;
System.out.println("Resultado: "+read());
System.out.println(LeerDatos(inInput));

inOutput.write("ADMIN".getBytes());
System.out.println("Resultado2: "+read());
System.out.println(LeerDatos(inInput));


inOutput.write("PASS".getBytes());
System.out.println("Resultado2: "+read());
System.out.println(LeerDatos(inInput));

inOutput.write("?".getBytes());
System.out.println("Resultado4: "+read());
System.out.println(LeerDatos(inInput));

inOutput.write("info configure system".getBytes());
System.out.println("Resultado4: "+read());
System.out.println(LeerDatos(inInput));
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String LeerDatos(InputStream sIn) throws IOException
{
String respuesta="";
int c;
byte[] reply = { (byte) 255};

int fin = sIn.available();
//System.out.println("1: "+sIn.available());
//System.out.println("2: "+sIn.hashCode());
for(int i = 0; i<fin;i++)
//String aux=null;
//while((aux = sIn.toString())!=null)
{
try
{
//System.out.println("reply["+i+"]: "+(byte) sIn.read());
c = sIn.read();
char s1 = (char)c;
respuesta += s1;
//System.out.println("Caracter "+s1 +" Fin Caracter");
}
catch(IOException e)
{
System.out.println("No se pudo leer con read() "+e);
}
}

return respuesta;
}
public int read() throws IOException
{
byte b;

b = (byte) input.read();
if ( b != IAC )
{
System.out.println("NOT IAC "+b);
return b;
} // not an IAC, skip.

b = (byte) input.read();
if ( b == IAC ) {System.out.println("TWO IACS isn't IAC "+b);return b;} // two IACs isn't.

if ( b != SB ) // handle command
{
}

return read();
}

public void close() throws IOException
{
input.close();
}

private void write( byte inByte ) throws IOException
{
output.write( inByte );
output.flush();
}

private void write( byte[] inBytes ) throws IOException
{
output.write( inBytes );
output.flush();
}

// iac commands
public static void main(String[] arg)
{
try
{
Socket s = new Socket("172.18.184.85",23);
System.out.println(s);
input = new DataInputStream(s.getInputStream());
output = new DataOutputStream(s.getOutputStream());
TelnetInputStream dir = new TelnetInputStream(input, output);

}
catch(IOException e)
{
System.out.println("Error "+e);
}
}
}
  #2 (permalink)  
Antiguo 30/05/2007, 15:10
 
Fecha de Ingreso: octubre-2003
Mensajes: 3.578
Antigüedad: 20 años, 6 meses
Puntos: 51
Re: Telnet en java

Yo la vez que implemente algo parecido lo que hice fue implementar usar un timeout, o sea esperar un tiempo configurable. Dado que la comunicación por telnet no es un "protocolo fijo" (a nivel de comunicación por encima, no el protocolo en si) y no puedes saber a priori el tamaño de lo que te van a mandar... pues mucho más no se me ocurrió.

S!
  #3 (permalink)  
Antiguo 30/05/2007, 15:42
 
Fecha de Ingreso: febrero-2006
Mensajes: 35
Antigüedad: 18 años, 3 meses
Puntos: 0
Re: Telnet en java

y como hiciste el timeout?
  #4 (permalink)  
Antiguo 31/05/2007, 00:18
 
Fecha de Ingreso: octubre-2003
Mensajes: 3.578
Antigüedad: 20 años, 6 meses
Puntos: 51
Re: Telnet en java

Nada sofisticado, puse un sleep para esperar un numero determinado de segundos y despues leer del InputStream la respuesta del servidor, suponiendo que en ese tiempo ya habria terminado de responder.

No es la forma más eficiente de comunicación, pero no hay mucho más que hacer con un Telnet, a no ser que sepas exactamente lo que te van a responder y puedas detectarlo a medida que lees la respuesta (por ejemplo si sabes que te van a devolver n lineas de texto, podrías leer esas y listo).

S!
  #5 (permalink)  
Antiguo 31/05/2007, 13:49
 
Fecha de Ingreso: febrero-2006
Mensajes: 35
Antigüedad: 18 años, 3 meses
Puntos: 0
Re: Telnet en java

Gracias por tu respuesta, podrias poner un ejemplo de prueba porque no logro que funcione igualmente.
  #6 (permalink)  
Antiguo 31/05/2007, 15:17
 
Fecha de Ingreso: octubre-2003
Mensajes: 3.578
Antigüedad: 20 años, 6 meses
Puntos: 51
Re: Telnet en java

Suponiendo que "theTC" es un org.apache.commons.net.telnet.TelnetClient; con una conexión abierta, yo lo hacía así:
Código:
	/**
	 * @param command
	 * @param timeout
	 * @return @throws
	 *         IOException
	 * @throws InterruptedException
	 */
	public List executeCommand(
			String command, long timeout)
			throws IOException, InterruptedException
	{
		List answerLines = new ArrayList();
		if (started)
		{
			OutputStream theOS = theTC.getOutputStream();
			theOS.write((command + "\n").getBytes());
			theOS.flush();
			Thread.sleep(timeout);
			ByteArrayInputStream theBAIS = new ByteArrayInputStream(theTAR
					.getResult());
			InputStreamReader theISR = new InputStreamReader(theBAIS);
			BufferedReader theBR = new BufferedReader(theISR);
			String theLine = null;
			while ((theLine = theBR.readLine()) != null)
			{
				answerLines.add(theLine);
			}
		}
		return answerLines;
	}
Y el método ejecutado en un Thread distinto del programa principal, para que no se quedara colgado esperando.

S!
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 06:21.