Java Socket : java.net.SocketTimeoutException: Read timed out
<p>Hi I hope you guys are doing great.</p>

<p>I'm currently trying to test a service class that creates a socket connection to a print server.</p>

<p>Here's the service class : </p>

<pre><code>public class PrintServiceImpl implements PrintService {
private static final Logger LOGGER = LoggerFactory.getLogger(PrintServiceImpl.class);

static final int TIMEOUT_MILLISECOND = 20000;

@Override
public boolean sendLabelToPrintServer(String hostname, int port, String labelData) {

    Socket clientSocket = null;
    DataOutputStream outToServer = null;
    Boolean successful;

    try {
        // open the connection to the printing server
        clientSocket = new Socket();
        clientSocket.connect(new InetSocketAddress(hostname, port), TIMEOUT_MILLISECOND);
        clientSocket.setSoTimeout(TIMEOUT_MILLISECOND);

        outToServer = new DataOutputStream(clientSocket.getOutputStream());

        // send data to print
        outToServer.writeBytes(labelData);

        BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(),
                StandardCharsets.UTF_8));

        // Read HTTP Request CHARACTER BY CHARACTER instead of line by line
        while ((char) input.read() != 0 &amp;&amp; (char) input.read() != '\r') {
            LOGGER.debug("Getting print server answer.");
        }

        successful = true;
        LOGGER.debug("Label printed.");
    } catch (Exception e) {
        LOGGER.error("Printing failed.", e);
        successful = false;
    } finally {
        try {
            // close connection
            if (outToServer != null) {
                outToServer.close();
            }
            if (clientSocket != null) {
                clientSocket.close();
            }
        } catch (IOException e) {
            LOGGER.error("Exception while closing DataOutputStream/ClientSocket.", e);
        }
    }
    return successful;
}
</code></pre>

<p>And here's my test class. As you can see the @Before method instantiates a SocketServer on a new Thread.</p>

<pre><code>public class PrintServiceImplTest {

private static final Logger LOGGER = LoggerFactory.getLogger(PrintServiceImplTest.class);

PrintServiceImpl whfPrintService = new PrintServiceImpl();

private static final String LOCALHOST = "localhost";
private static final int SERVER_PORT = 3000;
private static final String LABEL_TEXT = "This dummy text is sent to the print server";
private static final String RESPONSE = "Test Label printed correctly";
private ServerSocket server;
private Socket incommingSocket = null;

@Before
public void before() {
    Thread myThread = new Thread() {
        @Override
        public void run() {
            try {
                server = new ServerSocket(SERVER_PORT);
                incommingSocket = server.accept();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };
    myThread.start();
}

@After
public void after() {
    try {
        incommingSocket.close();
        server.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

@Test
public void returnsTrueIfConnectionSuccessful() {

    BufferedReader reader = null;
    PrintWriter out = null;
    BufferedReader in = null;
    String line;

    whfPrintService.sendLabelToPrintServer(LOCALHOST, SERVER_PORT, LABEL_TEXT);

    try {

        in = new BufferedReader(new InputStreamReader(incommingSocket.getInputStream()));
        out = new PrintWriter(incommingSocket.getOutputStream());

        reader = new BufferedReader(new InputStreamReader(incommingSocket.getInputStream()));

        while ((line = reader.readLine()) != null) {
            System.out.println("line : " + line);
        }

        out.write(RESPONSE);
        out.flush();

        out.close();
        in.close();
        reader.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}
</code></pre>

<p>When I run the test, I get a SocketTimoutException. It occurs when the client is reading the response from the server. This line :</p>

<pre><code>while ((char) input.read() != 0 &amp;&amp; (char) input.read() != '\r') {
</code></pre>

<p>So this means that the client does not receive a response. My guess is that the server does not send a correct response.</p>

<p>What am I missing ? thank you in advance.</p>