Java套接字连接关闭而不调用关闭连接
我有一个服务器和客户端套接字应用程序,如下所示Java套接字连接关闭而不调用关闭连接,java,sockets,junit,serversocket,Java,Sockets,Junit,Serversocket,我有一个服务器和客户端套接字应用程序,如下所示 public class ServerApp { public void start(int port) throws IOException { serverSocket = new ServerSocket(port); clientSocket = serverSocket.accept(); out = new Prin
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);
}
}
问题是,即使我执行一次单元测试,服务器连接也会断开。我没有明确指定要关闭的套接字
我还想在我的测试用例中添加以下内容,但由于服务器连接断开,只有第一次执行成功,第二次执行失败
@测试(invocationCount=5,threadPoolSize=3)您的服务器只接受一个连接。在响应第一个客户端之后,它停止接收连接。为了持续连接到服务器,您需要将accept例程放入一个循环中Define'getdisconnect'。这里没有任何东西可以检测到这一点。