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(() -> {
35 clientSocket.set(new TextSocket(serverSocket.accept()));
40 public List<String> collectUntil(Matcher<String> lineMatcher) throws IOException {
41 return clientSocket.get().collectUntil(lineMatcher);
44 public void writeLine(String... lines) throws IOException {
45 for (String line : lines) {
46 clientSocket.get().writeLine(line);
50 public String readLine() throws IOException {
51 return clientSocket.get().readLine();
55 public void close() throws IOException {
56 clientSocket.get().close();