我有两个使用套接字的单元测试。问题是当我在 Eclipse 中执行它们时,我总是在第二个客户端/服务器测试中出现连接被拒绝错误。第一个单元测试使用端口 9091,第二个使用端口 9092。
java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
快速的解决方案是Thread.sleep(500)
在第二个单元测试开始时添加。它大多有效,但并非总是如此。
这个错误有什么问题?如何安全地执行多个使用套接字的单元测试?
@Test(timeout = 2000)
public void testBareTest9092() {
PingerThread pinger = new PingerThread();
pinger.start();
String serverAddress = "localhost";
String testString = "ABCDEF-Hellowrolds";
try {
Socket s = new Socket(serverAddress, 9092);
PrintWriter output = new PrintWriter(s.getOutputStream(), true);
output.println(testString);
BufferedReader input = new BufferedReader(new InputStreamReader(
s.getInputStream()));
String answer = input.readLine();
System.out.println(answer);
System.out.println(testString);
assertTrue(answer.equals(testString));
s.close();
input.close();
output.close();
} catch (UnknownHostException e) {
e.printStackTrace();
fail("ERROR!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
fail("ERROR!");
}
pinger.cancel();
}
public class PingerThread extends Thread {
public int id;
@Override
public void run() {
try {
ServerSocket listener = new ServerSocket(9092);
long startTime = System.nanoTime();
while (!Thread.currentThread().isInterrupted()) {
try {
while (true) {
Socket socket = listener.accept();
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
String input = in.readLine();
System.out.println("Received:" + input);
PrintWriter out = new PrintWriter(
socket.getOutputStream(), true);
out.println(input);
} finally {
socket.close();
listener.close();
}
}
} finally {
}
}
} catch (Exception consumed) {
}
}
public void cancel() {
interrupt();
}
}