Java 关闭套接字连接而不调用关闭连接
Java Socket connection get close with out invoke close connection
我有如下服务器和客户端套接字应用程序,
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;
}
}
单元测试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);
}
}
问题是即使我执行了一次单元测试,服务器连接也断开了。我没有明确指定要关闭的套接字。
我还想在我的测试用例中添加以下内容,但只有第一次执行成功,第二次执行失败,因为服务器连接断开。
@Test(invocationCount = 5, threadPoolSize = 3)
您的服务器只接受一个连接。响应第一个客户端后,它停止接收连接。为了持续连接到服务器,您需要将您的接受例程放入一个循环
我有如下服务器和客户端套接字应用程序,
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;
}
}
单元测试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);
}
}
问题是即使我执行了一次单元测试,服务器连接也断开了。我没有明确指定要关闭的套接字。
我还想在我的测试用例中添加以下内容,但只有第一次执行成功,第二次执行失败,因为服务器连接断开。
@Test(invocationCount = 5, threadPoolSize = 3)
您的服务器只接受一个连接。响应第一个客户端后,它停止接收连接。为了持续连接到服务器,您需要将您的接受例程放入一个循环