我正在尝试为我编写的服务器/客户端编写 JUnit 测试,因此我创建了充当服务器的 Runnable,而我当前的线程充当客户端。在尝试写入客户端套接字的输出流之前,我在服务器 Runnable 上调用 start()。但是,我的程序总是在之后终止Socket client = new Socket("hostname", 0);
,我不知道为什么。我的猜测是这是因为我试图在同一个测试中创建一个套接字和客户端?因此,将 ip 绑定为客户端并同时监听该 ip 会导致异常行为吗?这个对吗?我该如何解决这个困境?
public void test() {
int result;
String strMsg = "dasda";
try {
Thread serverThread = new Thread(new ServerRunnable());
serverThread.start();
Socket client = new Socket("hostname", 0);
OutputStream os = client.getOutputStream();
os.write(strMsg.getBytes());
InputStream is = client.getInputStream();
while (true){
result = is.read();
ByteBuffer bb = ByteBuffer.allocate(4);
bb.putInt(result);
String input = new String(bb.array());
if (input=="Success") return;
}
} catch (IOException e1){
fail("IOException on client");
}
}
class ServerRunnable implements Runnable {
ServerSocket server;
public ServerRunnable(){
server = new ServerSocket(0);
}
public void run(){
try {
active = true;
while (active) {
Socket sock = server.accept();
}
} catch (IOException e1){
fail("IOException in Server");
}
}
}