2012-10-25 41 views
3

我正試圖編寫一個程序來偵聽正在運行的計算機上的端口4444,並記錄所有傳入數據。無法從端口讀取數據,InputStream掛起

這是我的代碼到目前爲止。

import java.io.*; 
import java.net.*; 

public class Foo { 
URL url; 
URLConnection connection; 
InputStreamReader stream; 
BufferedReader in; 
String inputLine; 
int test = 0; 

public Foo() 
{ 
    Connect(); 
} 

public static void main(String[] args) 
{ 
    Foo bridge = new Foo(); 
    System.out.println("made the class"); 
    for(;;) 
    { 
     System.out.println("in the loop"); 
     try 
     { 
      System.out.println("making the try"); 
      if((bridge.inputLine = bridge.in.readLine()) != null) 
      { 
       System.out.println("reading the line"); 
       System.out.println(bridge.inputLine); 
      } 
     } 
     /*catch(NullPointerException n) 
     { 
      System.out.println(bridge.test); 
      bridge.test++; 
     }*/ 
     catch(Exception e) 
     { 
      System.out.println("MAIN" + e); 
     } 
    } 
} 

public int Connect() 
{  
    try 
    { 
     System.out.println("starting the constructor"); 
     URL url = new URL("http", "192.168.0.104", 4444, ""); 
     System.out.println("url ready"); 
     URLConnection connection = url.openConnection(); 
     System.out.println("connection ready"); 
     //connection.setReadTimeout(5000); 
     connection.setDoInput(true); 
     InputStreamReader stream = new InputStreamReader(connection.getInputStream()); 
     System.out.println("stream ready"); 
     BufferedReader in = new BufferedReader(stream); 
     //BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); 
     System.out.println("bufferReader ready"); 

     return 0; 
    } 
    catch(Exception e) 
    { 
     System.out.println("CON" + e); 
    } 
    return 1; 
} 
} 

當我運行它時,我得到這個作爲輸出。

D:\temp_104\foo>java -cp . foo 
starting the constructor 
url ready 
connection ready 

它每次嘗試創建輸入流時都會掛起。 我用超級終端測試了它,服務器正在輸出消息並可以連接到端口4444上。我運行java 1.5.0_15並且無法更新。

任何人都可以看到我做錯了什麼?

+0

你可以在流程上運行jstack併發布它掛起的位置嗎? –

+0

我對jstack不熟悉,如何在程序中運行它? – Skeith

+0

它是jdk的一部分。 'jstack [PID]'將轉儲痕跡。或者如果你在調試器中運行它,你可以看看那裏的痕跡。或者你可以嘗試首先創建你的輸入流(connection.getInputStream()),看它是否掛在那裏。 –

回答

0

我發現問題是範圍。緩衝讀取器在函數中被初始化好了,但是一旦回到主函數中,它就是空的。

2

您正在閱讀使用BufferedReader的行。服務器是否在每封郵件的末尾寫入換行符?

+0

你打算說BufferedReader嗎? :) – linski

+0

我不明白這是多麼重要的程序崩潰在inputstreams構造函數它從來沒有讀取任何東西。 – Skeith

+0

@Skeith,如果程序崩潰,那麼請發佈堆棧跟蹤 –