Java Socket连接通过关闭调用来关闭连接

时间:2018-07-01 07:14:58

标签: java sockets junit serversocket

我有以下服务器和客户端套接字应用程序,

   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;
    }
}

单元测试类,

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);
    }
}

问题是,即使我一次执行单元测试,服务器连接也会断开连接。我还没有明确指定要关闭的套接字。

我还想在测试用例中添加以下内容,但由于服务器连接已断开,只有第一个执行成功,第二个失败。

@Test(invocationCount = 5,threadPoolSize = 3)

1 个答案:

答案 0 :(得分:0)

您的服务器仅接受一个连接。响应第一个客户端后,它停止接收连接。为了持续连接到服务器,您需要将您的接受例程置于循环中