0
我在模擬連接到我的服務器套接字時遇到了一些麻煩,接受似乎繼續阻塞,因爲它不「看到」連接。ServerSocket接受繼續阻止
下面是一些簡單的代碼
@Test
public void testPDMServerThread() {
try {
ServerSocket serverSocket = new ServerSocket(0);
int port = serverSocket.getPort();
Socket clientSocket = new Socket("localhost", port);
PrintWriter clientRequest = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader serverResponse = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
serverThread = new ProducerMonitorServerThread(serverSocket.accept());
clientRequest.write("Hi!");
serverThread.start();
System.out.println("Server says: " + serverResponse.readLine());
assertEquals("RUNNABLE", serverThread.getState().toString());
} catch (IOException e) {
}
}
而這裏的線程所在服務器應該響應
public class ProducerMonitorServerThread extends Thread {
private Socket socket;
public ProducerMonitorServerThread(Socket socket) {
super("PDM");
this.socket = socket;
}
@Override
public void run() {
try {
PrintWriter serverResponse = new PrintWriter(socket.getOutputStream(), true);
BufferedReader clientRequest = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
String serverInput, clientOutput;
while((serverInput = clientRequest.readLine()) != null) {
clientOutput = "Bye!";
System.out.println("Client says: " +serverInput);
serverResponse.write(clientOutput);
}
serverResponse.close();
clientRequest.close();
socket.close();
} catch (IOException e) {
}
}
}
它似乎永遠不會讓過去這條線這就是爲什麼我認爲接受的是沒有看到的連接
serverThread = new ProducerMonitorServerThread(testServer.accept());
我敢肯定,有一些基本的東西,我只是沒有看不到。
啊哈!好大聲,我實際上正在處理例外情況,我只是簡化了一些代碼。該修復最後非常簡單,例如serverResponse.write(clientOutput),它應該是serverResponse.println(clientOutput),再次感謝! – PDStat