1 package expectj;
2
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.io.OutputStream;
6 import java.net.InetAddress;
7 import java.net.Socket;
8 import java.net.UnknownHostException;
9
10 /***
11 * A Spawnable for controlling a telnet session using ExpectJ.
12 * @author Johan Walles
13 */
14 class TelnetSpawn extends AbstractSpawnable implements Spawnable {
15 /***
16 * A reference to the remote host.
17 */
18 private InetAddress m_remoteHost;
19
20 /***
21 * The port we're talking to on the remote host.
22 */
23 private int m_remotePort;
24
25 /***
26 * Our communications channel to the remote host.
27 */
28 private Socket m_socket;
29
30 /***
31 * Use this to read data from the remote host.
32 */
33 private InputStream m_fromSocket;
34
35 /***
36 * Use this to write data to the remote host.
37 */
38 private OutputStream m_toSocket;
39
40 /***
41 * Construct a new telnet spawn.
42 * @param remoteHostName The remote host to connect to.
43 * @param remotePort The remote port to connect to.
44 * @throws UnknownHostException If the name of the remote host cannot be looked up
45 */
46 public TelnetSpawn(String remoteHostName, int remotePort) throws UnknownHostException {
47 m_remotePort = remotePort;
48 m_remoteHost = InetAddress.getByName(remoteHostName);
49 }
50
51 public void start() throws IOException {
52 m_socket = new Socket(m_remoteHost, m_remotePort);
53 m_fromSocket = m_socket.getInputStream();
54 m_toSocket = m_socket.getOutputStream();
55 }
56
57 public InputStream getStdout() {
58 return m_fromSocket;
59 }
60
61 public OutputStream getStdin() {
62 return m_toSocket;
63 }
64
65 public InputStream getStderr() {
66 return null;
67 }
68
69 public boolean isClosed() {
70 if (m_socket != null) {
71 if (m_socket.isClosed()) {
72
73 stop();
74 }
75 }
76 return m_socket == null;
77 }
78
79 public int getExitValue() {
80 return 0;
81 }
82
83 public void stop() {
84 if (m_socket == null) {
85 return;
86 }
87
88 try {
89 m_socket.close();
90 } catch (IOException ignored) {
91
92 }
93 m_socket = null;
94 m_fromSocket = null;
95 m_toSocket = null;
96 }
97 }