package net.bourgau.philippe.concurrency.kata;

import org.apache.commons.io.IOUtils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

public class TextLineProtocol implements AutoCloseable {
    private final Socket socket;
    private BufferedReader reader;
    private BufferedWriter writer;

    public TextLineProtocol(Socket socket) throws Exception {
        this.socket = socket;
        reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    }

    public void writeMessage(String message) throws Exception {
        writer.write(message + "\n");
        writer.flush();
    }

    public String readMessage() throws Exception {
        return reader.readLine();
    }

    @Override
    public void close() {
        IOUtils.closeQuietly(socket);
    }
}

@@ -234,16 +234,89 @@
 .Socket;
+%0Aimport java.net.SocketException;%0Aimport java.net.SocketTimeoutException;
 %0A%0Apublic
@@ -558,24 +558,58 @@
 t = socket;%0A
+        socket.setSoTimeout(250);%0A
         read
@@ -971,32 +971,430 @@
     
-return reader.readLine()
+String message = null;%0A        while (!Thread.interrupted()) %7B%0A            try %7B%0A                message = reader.readLine();%0A                break;%0A            %7D catch (SocketTimeoutException ignoreTimeoutAndRetry) %7B%0A                continue;%0A            %7D%0A        %7D%0A        if (message == null) %7B%0A            throw new SocketException(%22Socket was closed before a message could be read%22);%0A        %7D%0A        return message
 ;%0A  

Make reading from sockets more robust