I had to build a client application in Java that is able to communicate through a Telnet protocol with a SpeedTouch modem.
The goal was to find if there is already some kind of framework or library in Java that supports Telnet communication.
Apache offers a neat library called Apache Commons Net. This library supports communication with all sorts of network protocols like FTP / SFTP, POP3, Telnet and so on.
Here’s a client class that supports Telnet communication with the help of the Apache tool.
import java.io.InputStream;
import java.io.PrintStream;
import nl.yenlo.speedtouch.exception.TelnetTerminalException;
import org.apache.commons.net.telnet.TelnetClient;
/**
*
* @author Steve Liem
*/
public class AutomatedTelnetClient {
private TelnetClient telnet = new TelnetClient();
private InputStream in;
private PrintStream out;
private String prompt = “>”;
public AutomatedTelnetClient(String server, String user, String password) throws Exception {
// Connect to the specified server
telnet.connect(server, 23);
// Get input and output stream references
in = telnet.getInputStream();
out = new PrintStream(telnet.getOutputStream());
// Log the user on
readUntil(“Username : “);
write(user);
readUntil(“Password : “);
write(password);
// Advance to a prompt
readUntil(prompt);
}
public String readUntil(String pattern) throws Exception {
char lastChar = pattern.charAt(pattern.length() – 1);
StringBuffer sb = new StringBuffer();
char ch = (char) in.read();
while (true) {
System.out.print(ch);
sb.append(ch);
if (sb.toString().endsWith(“Closing connection”)) {
throw new TelnetTerminalException(“Wrong Telnet arguments passed”);
}
if (sb.toString().endsWith(prompt) && !pattern.equals(prompt)) {
return sb.toString();
}
if (ch == lastChar) {
if (sb.toString().endsWith(pattern)) {
return sb.toString();
}
}
ch = (char) in.read();
}
}
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();
}
}
}
Also I couldn’t find any special exception class for throwing exceptions when the telnet client breaks the protocol. So here is an own written exception to throw in such cases:
/**
* Used for throwing an Excpetion when a wrong Telnet command is executed.
*
* @author Steve Liem
*/
public class TelnetTerminalException extends Exception {
private static final long serialVersionUID = -2969598230165607465L;
public TelnetTerminalException() {
super();
}
public TelnetTerminalException(String msg) {
super(msg);
}
}
This was exactly what I was looking for! Thank you so much for sharing this!