2015-10-31 69 views
1

我無法從套接字獲取輸入和輸出流,每次到達getInputStream/getOutputStream時,都會顯示我的代碼塊。ObjectInputStream在Java線程中失敗

class Connection implements Runnable { 
    private static final Logger logger = Logger.getLogger(Connection.class.getName()); 
    Socket connection = null; 
    Boolean serverIsDown = false; 
    Thread thread = null; 
    ObjectInputStream ois = null; 
    ObjectOutputStream oos = null; 
    Context ctx = null; 

    public Connection(Socket accept, Boolean serverIsDown) { 
     logger.log(Level.INFO, "Connected" + accept.getRemoteSocketAddress()); 
     this.connection = accept; 
     this.serverIsDown = serverIsDown; 

     this.thread = new Thread(this, "Client Connection"); 
     this.thread.start(); 

    } 

    public void init() throws IOException { 
     while (true) { 
      System.out.println("Hit enter to send object"); 
      System.in.read(); 
      Request request = new Request(); 
      oos.writeObject(request); 
     } 
    } 

    @Override 
    public void run() { 
     try { 
      this.ois = new ObjectInputStream(this.connection.getInputStream()); //Blocks here 
      this.oos = new ObjectOutputStream(this.connection.getOutputStream()); 
      this.init(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

當它阻塞時沒有輸出錯誤。

+1

始終平齊()用ObjectOutputStream創建ObjectInputStream的之前。這是因爲格式有一個ObjectInputStream在構造函數中讀取的頭。 –

回答

2

如所提到的文檔: http://docs.oracle.com/javase/7/docs/api/java/io/ObjectInputStream.html#ObjectInputStream(java.io.InputStream)

創建一個的ObjectInputStream從指定的InputStream讀取。 從流中讀取序列化流頭並進行驗證。此構造函數將會阻塞,直到相應的ObjectOutputStream寫入並刷新標頭

我建議你使用兩個線程處理來自接受套接字的輸入和輸出流,以避免阻塞。另一種更好的方法是使用線程池和一些異步io(ex; selector),而不是爲每個接受的套接字分配一個線程。

還參考以下的其它後: new ObjectInputStream() blocks