kamaci
kamaci

Reputation: 75137

Server - Client Data Exchange Test via Socket at JUnit

I'm trying to test a server - client data exchange via socket at my JUnit class. I've followed that:

private static Socket clientSocket;
private static InputStream is;
private static PrintWriter pw;
private static Socket serverSocket;
private static final int PORT_NUMBER = 1154;

@BeforeClass
public static void init() throws IOException {
    ServerSocket sSocket = new ServerSocket(PORT_NUMBER);
    clientSocket = new Socket("localhost", PORT_NUMBER);
    is = clientSocket.getInputStream();

    serverSocket = sSocket.accept();
    OutputStream os = serverSocket.getOutputStream();
    pw = new PrintWriter(os, true);
}

@Test
public void testXPackage() throws IOException {
    for (int packageByte : X_PACKAGE) {
        pw.write(packageByte);
    }

    while (is.available() > 0) {
        System.out.println(is.read());
    }
}

However is.available() is always 0. What I'm missing?

Upvotes: 1

Views: 1160

Answers (1)

President James K. Polk
President James K. Polk

Reputation: 41967

The PrintWriter pm is buffering output. You must call pm.flush() when you have finished writing. So for example:

@Test
public void testXPackage() throws IOException {
    for (int packageByte : X_PACKAGE) {
        pw.write(packageByte);
    }
    pm.flush(); // <<--- added this line.

    while (is.available() > 0) {
        System.out.println(is.read());
    }
}

Upvotes: 1

Related Questions