1 package net.pterodactylus.fcp.fake;
3 import java.io.IOException;
4 import java.net.ServerSocket;
6 import java.util.concurrent.ExecutorService;
7 import java.util.concurrent.Future;
8 import java.util.concurrent.atomic.AtomicReference;
10 import org.hamcrest.Matcher;
15 * @author <a href="bombe@freenetproject.org">David ‘Bombe’ Roden</a>
17 public class FakeTcpServer implements AutoCloseable {
19 private final ServerSocket serverSocket;
20 private final ExecutorService executorService;
21 private final AtomicReference<TextSocket> clientSocket = new AtomicReference<>();
23 public FakeTcpServer(ExecutorService executorService) throws IOException {
24 this.executorService = executorService;
25 this.serverSocket = new ServerSocket(0);
28 public int getPort() {
29 return serverSocket.getLocalPort();
32 public Future<?> connect() throws IOException {
33 return executorService.submit(() -> {
34 clientSocket.set(new TextSocket(serverSocket.accept()));
39 public List<String> collectUntil(Matcher<String> lineMatcher) throws IOException {
40 return clientSocket.get().collectUntil(lineMatcher);
43 public void writeLine(String... lines) throws IOException {
44 for (String line : lines) {
45 clientSocket.get().writeLine(line);
49 public String readLine() throws IOException {
50 return clientSocket.get().readLine();
54 public void close() throws IOException {
55 TextSocket textSocket = clientSocket.get();
56 if (textSocket != null) {