2009-10-12 27 views
0

我的代碼看起來是這樣的,這是服務器代碼(Runnable的Java:插座緊密連接和ObjectInputStream的

public void run() { 
    while (true) { 
     try { 
      System.out.println("Waiting for client..."); 
      this.socket = serverSocket.accept(); 
      System.out.println("Client accepted"); 
      while (true) { 
       readCommand(); 
       try { 
        Thread.sleep(2); 
       } catch (Exception e) { 
       } 
      } 
     } catch (Exception ex) { 
      Main.error("Server stopped for current host", ex); 
     } 
    } 
} 

我的問題是:當客戶端關閉連接,他仍然在等待中readCommand();讀取命令直到一個命令被髮送並且將拋出一個EOFException。這是我的readCommand方法:

private void readCommand() throws Exception { 
    Object o = new ObjectInputStream(socket.getInputStream()).readObject(); 
    if (o instanceof Command) { 
     ((Command) o).execute(); 
     return; 
    } 
    if (o instanceof Recorder) { 
     System.out.println("Recording received"); 
     ((Recorder) o).executeRecord(); 
     return; 
    } 
    if (o instanceof MyKeyEvent) { 
     ((MyKeyEvent) o).execute(); 
     return; 
    } 
} 

所以我覺得讀它來檢查,如果連接是打開之前。

編輯:如果我評價run - 方法的代碼中,EOFExceptiontry-catch-body拋出。但他停止接受客戶。

回答

3

EOFException正是我期望的,如果客戶端關閉連接。所以我不太確定你的問題實際上是。也許您需要區分預期的客戶端斷開連接和意外的客戶端斷開連接。在這種情況下,您應該發送某種End-of-message對象來標記傳輸的結束?

如果你想檢查信息是否可用,那麼在流上有一個available()方法。我不認爲你需要你的Thread.sleep(2),順便說一句,因爲我希望有一個有效的輸入流在沒有數據的情況下掛起。

+0

程序需要'Thread.sleep(2)' – 2009-10-12 18:55:51

+0

'End-of-connection'是一個解決方案謝謝。 – 2009-10-12 19:04:40

+0

這很好。很高興知道它現在正在工作。 – 2009-10-12 19:14:54

0

你也可以 「只」 增加一個的try-catch趕上只是EOFException類

public void run() { 
    while (true) { 
     try { 
      System.out.println("Waiting for client..."); 
      this.socket = serverSocket.accept(); 
      System.out.println("Client accepted"); 
      try { 
       while (true) { 
        readCommand(); 
        try { 
         Thread.sleep(2); 
        } catch (Exception e) { 
        } 
       } 
      } catch (EOFException ex) { 
       System.out.println("client closed"); 
      } 
     } catch (Exception ex) { 
      Main.error("Server stopped for current host", ex); 
     } 
    } 
} 

肯定的是,最終的命令是要聰明得多/優雅...
[]]

+0

或者只是一個額外的捕獲。你不需要第二次「嘗試」。 – EJP 2014-02-24 07:16:12