added learnlibloblab
[tt2015.git] / a4 / code / src / learner / SocketSUL.java
1 package learner;
2
3 import java.io.BufferedReader;
4 import java.io.IOException;
5 import java.io.InputStreamReader;
6 import java.io.PrintWriter;
7 import java.net.InetAddress;
8 import java.net.Socket;
9 import java.net.UnknownHostException;
10
11 import de.learnlib.api.SUL;
12 import de.learnlib.api.SULException;
13
14 /**
15 * Socket interface to connect to an SUT/test adapter over TCP.
16 *
17 * As an example, type into a unix terminal "nc -vl {ip} {port}" (where {ip} and
18 * {port} are the chosen values), and run this socketSUL. You can now control the
19 * SUL through the terminal.
20 * @author Ramon Janssen
21 */
22 public class SocketSUL implements SUL<String, String>, AutoCloseable {
23 private final BufferedReader SULoutput;
24 private final PrintWriter SULinput;
25 private final Socket socket;
26 private final boolean extraNewLine;
27 private final String resetCmd;
28
29 /**
30 * Socket-interface for SUTs. Connects to a SUT (or test-adapter)
31 * @param ip the ip-address
32 * @param port the tcp-port
33 * @param extraNewLine whether to print a newline after every input to the SUT
34 * @param resetCmd the command to send for resetting the SUT
35 * @throws UnknownHostException
36 * @throws IOException
37 */
38 public SocketSUL(InetAddress ip, int port, boolean extraNewLine, String resetCmd) throws UnknownHostException, IOException {
39 this.socket = new Socket(ip, port);
40 this.SULoutput = new BufferedReader(new InputStreamReader(socket.getInputStream()));
41 this.SULinput = new PrintWriter(socket.getOutputStream(), true);
42 this.extraNewLine = extraNewLine;
43 this.resetCmd = resetCmd;
44 }
45
46 @Override
47 public void post() {
48 if (extraNewLine) {
49 this.SULinput.write(this.resetCmd + System.lineSeparator());
50 } else {
51 this.SULinput.write(this.resetCmd);
52 }
53 this.SULinput.flush();
54 }
55
56 @Override
57 public void pre() {
58
59 }
60
61 @Override
62 public String step(String input) throws SULException {
63 if (extraNewLine) {
64 this.SULinput.write(input + System.lineSeparator());
65 } else {
66 this.SULinput.write(input);
67 }
68 this.SULinput.flush();
69 try {
70 return this.SULoutput.readLine();
71 } catch (IOException e) {
72 throw new SULException(e);
73 }
74 }
75
76 @Override
77 public void close() throws Exception {
78 this.socket.close();
79 }
80 }