我知道這個問題已被問了好幾次了。然而,在遵循所有其他問題的建議之後,我仍然堅持問題是什麼。新ObjectInputStream導致掛起/超時
我有一個服務器和客戶端。一個簡單的ping/pong程序。運行服務器,然後運行客戶端,並給它一些時間來運行它的過程中,超時異常開始被拋出時不時...
超時有防止塊,但是,如果刪除,它會導致程序停頓。
有沒有辦法來防止這種情況發生?
Server.java
public static void main(String args[]) {
try {
ServerSocket serverSocket = new ServerSocket(3000);
while (true) {
Socket socket = serverSocket.accept();
String message = null;
try {
socket.setSoTimeout(3000);
try (ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream())) {
message = (String) objectInputStream.readObject();
System.out.println("Server received " + message);
}
socket.close();
} catch (IOException | ClassNotFoundException ex) {
//This exception is thrown because it hangs, but why does it hang?
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
if ((message != null) && (message.equals("Ping"))) {
try {
Socket pongSocket = new Socket("localhost", 3000);
pongSocket.setSoTimeout(3000);
try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(pongSocket.getOutputStream())) {
objectOutputStream.writeObject("Pong");
objectOutputStream.flush();
System.out.println("Server sent Pong");
}
pongSocket.close();
continue;
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
Client.java
public static void main(String args[]) {
while (true) {
try {
Socket pingSocket = new Socket("localhost", 3000);
pingSocket.setSoTimeout(3000);
try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(pingSocket.getOutputStream())) {
objectOutputStream.writeObject("Ping");
System.out.println("Client sent Ping");
objectOutputStream.flush();
}
pingSocket.close();
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
除了沖水()ANS迅速一部分,看看這個問題:http://stackoverflow.com/questions/33106127/swift-socket-readline-writeline/33106252#3310 6252。一旦serverSocket.accept()調用創建一個新的Socket,我更願意創建一個線程來處理IO。創建一個線程並傳遞客戶端Socket並在那裏執行你的IO –