Connecting to a Telnet session

Lee Painter

If you need to connect your terminal to the Legacy Telnet protocol we provide a basic implementation of a Telnet client based on Apache Commons Net API in the core terminal module. This provides basic support for telnet with some extensions to the core apache TelnetClient class to help this work with our terminal renderers. 

You can instantiate the Telnet client with the following code. In this example, the display variable is a reference to one of the terminal renderers, such as the SwingTerminalPanel.

TelnetClientImpl telnet = new TelnetClientImpl(display.getVDUBuffer());

Then simply connect it to a telnet server

telnet.connect("towel.blinkenlights.nl");

As discussed in the integration article you should then connect the streams of the client to the terminal buffer. 

Thread t2=  new Thread() {
  public void run() {
      try {
        IOUtils.copy(telnet.getInputStream(), new TerminalOutputStream(display.getVDUBuffer()));
      } catch (Exception e) {
      }
  }
};

t2.start();

/** IMPORTANT the Telnet OutputStream MUST be flushed after writing **/
int r;
TerminalInputStream in = new TerminalInputStream(display.getVDUBuffer());
byte[] buf = new byte[256];
while((r = in.read(buf)) > -1) {
   telnet.getOutputStream().write(r, 0, r);
   telnet.getOutputStream().flush();
}

Screen resizing

You can handle screen resizing by adding a listener to the terminal renderer and notifying the telnet server of the change

display.getVDUBuffer().addListener(new TerminalListenerAdapter() {
   public void screenResize(Terminal terminal, int cols, int rows, boolean remote) {
      if(!remote) {
        try {
            telnet.setScreenSize(cols, rows);
         } catch(IOException e) { }
      }
  }
});