java - Apache TelnetClient, InputStream unable to convert to String using Apache IOUtils -
i'm having trouble inputstream telnet session. have made connection, can send commands via telnet and, using system.out.println, can see receiving correct response.
i needed return responses session, string, need perform regex on verify value test.
import java.io.bufferedreader; import java.io.ioexception; import java.io.inputstream; import java.io.inputstreamreader; import java.io.printstream; import java.io.reader; import java.io.stringwriter; import java.io.writer; import java.net.socketexception; import org.apache.commons.io.ioutils; import org.apache.commons.net.telnet.telnetclient; public class telnetservice { private final string server; private final int port; private telnetclient telnet = new telnetclient(); private inputstream datain; private printstream dataout; private string prompt = "~$"; public telnetservice(string server, int port) { this.server = server.replace("http://", ""); this.port = port; } private void starttelnetsession() throws socketexception, ioexception { telnet.connect(server, port); datain = telnet.getinputstream(); dataout = new printstream(telnet.getoutputstream()); } public string gettelnetsessionasstring() { try { starttelnetsession(); loginuser(); readuntil(prompt); write("this_command"); readuntil(prompt); stringwriter writer = new stringwriter(); ioutils.copy(datain, writer, "utf-8"); dataout.flush(); datain.close(); dataout.close(); string received = writer.tostring(); telnet.disconnect(); return received; } catch (exception e) { e.printstacktrace(); } return null; } private void loginuser() { readuntil("login:"); write("foo"); readuntil("password:"); write("bar"); } private void write(string value) { try { dataout.println(value); dataout.flush(); system.out.println(value); } catch (exception e) { e.printstacktrace(); } } private string readuntil(string pattern) { try { char lastchar = pattern.charat(pattern.length() - 1); stringbuffer buffer = new stringbuffer(); char ch = (char) datain.read(); while (true) { system.out.print(ch); buffer.append(ch); if (ch == lastchar) { if (buffer.tostring().endswith(pattern)) { return buffer.tostring(); } } ch = (char) datain.read(); } } catch (exception e) { e.printstacktrace(); } return null; } } as is, whenever test runs calls class, appears 'hang' during the
ioutils.copy(datain, writer, "utf-8"); i'm sure there simple i'm missing. out there able help? appreciated!
as happens able solve issue - not how wished suitable enough simple test function.
i wrote telnet inputstream file rather system.out.print'ed it. allowed me read file string.
i'd still liked have solved issue - guess threading issue , i'm still never beginner haven't tackled that.
Comments
Post a Comment