1 package net.pterodactylus.fcp.fake;
3 import java.io.IOException;
4 import java.net.ServerSocket;
6 import java.util.concurrent.Callable;
7 import java.util.concurrent.ExecutorService;
8 import java.util.concurrent.Future;
9 import java.util.concurrent.atomic.AtomicReference;
11 import org.hamcrest.Matcher;
16 * @author <a href="bombe@freenetproject.org">David ‘Bombe’ Roden</a>
18 public class FakeTcpServer implements AutoCloseable {
20 private final ServerSocket serverSocket;
21 private final ExecutorService executorService;
22 private final AtomicReference<TextSocket> clientSocket = new AtomicReference<>();
24 public FakeTcpServer(ExecutorService executorService) throws IOException {
25 this.executorService = executorService;
26 this.serverSocket = new ServerSocket(0);
29 public int getPort() {
30 return serverSocket.getLocalPort();
33 public Future<?> connect() throws IOException {
34 return executorService.submit(new Callable<Void>() {
36 public Void call() throws Exception {
37 clientSocket.set(new TextSocket(serverSocket.accept()));
43 public List<String> collectUntil(Matcher<String> lineMatcher) throws IOException {
44 return clientSocket.get().collectUntil(lineMatcher);
47 public void writeLine(String line) throws IOException {
48 clientSocket.get().writeLine(line);
51 public String readLine() throws IOException {
52 return clientSocket.get().readLine();
56 public void close() throws IOException {
57 clientSocket.get().close();