Search code examples
javasocketsjunitserversocket

Java Socket connection get close with out invoke close connection


I have a server and client socket applications as below,

   public class ServerApp { 

        public void start(int port) throws IOException {
                serverSocket = new ServerSocket(port);
                clientSocket = serverSocket.accept();
                out = new PrintWriter(clientSocket.getOutputStream(), true);
                in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                String instr = in.readLine();
                //do somethings
                out.println("done")
        }

        public static void main(String[] args) throws IOException {
                ServerApp server = new ServerApp();
                server.start(6666);
        }
      }

public class ClientApp {

    public void startConnection(String ip, int port) throws UnknownHostException, IOException {
        clientSocket = new Socket(ip, port);
        out = new PrintWriter(clientSocket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    }

    public String sendMessage(String msg) throws IOException {
        out.println(msg);
        String resp = in.readLine();
        return resp;
    }
}

Unit test class,

public class UnitTest {
    @Test
    public void testSend() throws UnknownHostException, IOException {
        ClientApp client = new ClientApp();
        client.startConnection("127.0.0.1", 6666);
        String response = client.sendMessage("test msg");
        assertEquals("done", response);
    }
}

The problem is even when I execute unit test one time, the server connection also get disconnect. I haven not explicitly specify the sockets to be close.

I also want to add below to my test case but only the first execution get success and second one get failed because server connection is disconnected.

@Test(invocationCount = 5, threadPoolSize = 3)


Solution

  • Your server accepts only one connection. After responding to the first client, it stops receiving connections. In order to continuously connect to the server, you need to put your accept routine into a loop