目前我有一個basic MUD client四類:WeatherDriver
主類,並LineReader
把處理的InputStream
和LineParser
解析String
的Queue
的,而Connection
持有Apache telnet connection。這是基於Apache Weather Telnet example。何時停止讀取telnet輸入?
LineReader
如何知道何時停止閱讀InputStream
發送消息到WeatherDriver
開始解析?
LineReader:
package teln;
import static java.lang.System.out;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
public class LineReader {
private String prompt = "/[#]/";
public LineReader() {
}
public Queue<String> readInputStream(InputStream inputStream) throws IOException {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(inputStreamReader);
String line = br.readLine();
Queue<String> lines = new LinkedList<>();
while (line != null) { //never terminates...
sb.append(line);
line = br.readLine();
lines.add(line);
}
out.println(lines);
return lines;
}
public void setPrompt(String prompt) {
this.prompt = prompt; //need to determine EOL somehow...
}
}
連接:
package teln;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.SocketException;
import org.apache.commons.net.telnet.TelnetClient;
public class Connection {
private TelnetClient tc = new TelnetClient();
public Connection() {
}
public Connection(InetAddress h, int p, String prompt) throws SocketException, IOException {
tc.connect(h, p);
}
public InputStream getInputStream() {
return tc.getInputStream();
}
}
WeatherDriver:
package teln;
import static java.lang.System.out;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Properties;
import java.util.Queue;
public final class WeatherDriver {
private static Connection c;
private static LineReader lineReader = new LineReader();
private static LineParser lineParser = new LineParser();
public static void main(String[] args) throws UnknownHostException, SocketException, IOException {
Properties props = PropertiesReader.getProps();
InetAddress host = InetAddress.getByName(props.getProperty("host"));
int port = Integer.parseInt(props.getProperty("port"));
String prompt = props.getProperty("prompt");
out.println("connecting...");
c = new Connection(host, port, prompt);
InputStream inputStream = c.getInputStream();
out.println("got stream");
Queue<String> lines = lineReader.readInputStream(inputStream);
out.println("got lines");
lineParser.parseLines(lines);
out.println("parsed lines");
}
}
請看看我的解決方法。 – Thufir