2013-03-20 81 views
5

使用readLine()接收數據時,儘管在發送消息時使用.flush在消息 的末尾放置了「\ n」,但讀取我的消息的while循環仍然阻塞。 只有關閉套接字連接時,它纔會離開循環。BufferedReader readLine()blocks

這裏的客戶端代碼:

bos = new BufferedOutputStream(socket. 
      getOutputStream()); 
bis = new BufferedInputStream(socket. 
      getInputStream()); 
osw = new OutputStreamWriter(bos, "UTF-8"); 
osw.write(REG_CMD + "\n"); 
osw.flush(); 

isr = new InputStreamReader(bis, "UTF-8"); 
BufferedReader br = new BufferedReader(isr); 

String response = ""; 
String line; 

while((line = br.readLine()) != null){ 
    response += line; 
} 

和服務器的代碼:

BufferedInputStream is; 
BufferedOutputStream os; 

is = new BufferedInputStream(connection.getInputStream()); 
os = new BufferedOutputStream(connection.getOutputStream()); 

isr = new InputStreamReader(is); 

String query= ""; 
String line; 

while((line = br.readLine()) != null){ 
    query+= line; 
} 

String response = executeMyQuery(query); 
osw = new OutputStreamWriter(os, "UTF-8"); 

osw.write(returnCode + "\n"); 
osw.flush(); 

我在服務器端代碼塊while循環。 謝謝。

+0

把你的代碼放在try/catch塊中並關閉finally塊中的streams/connection。 – happy 2013-03-20 10:49:34

+1

這似乎沒有問題。你想知道爲什麼會發生這種行爲嗎?如何預防它? – Sinkingpoint 2013-03-20 10:54:14

+1

如果你只想讀一行爲什麼使用while循環? – 2013-03-20 10:56:12

回答

10

BufferedReader將繼續讀取輸入,直到它到達結尾(文件結尾或流或源等)。在這種情況下,'結束'是套接字的關閉。所以只要Socket連接打開,您的循環就會運行,並且BufferedReader將等待更多輸入,每次達到'\ n'時循環。

+0

mmm我並不認爲這個結束是關閉的插座。謝謝。現在我看着它,我誤解了文檔! – Majid 2013-03-20 10:57:51

+0

當涉及到非文件流的eof時,doc很模糊。 – Sinkingpoint 2013-03-20 10:59:09

+0

這是OP的循環,直到EOS讀取,而不是BufferedReader。 – EJP 2013-03-20 21:15:37

3

這是因爲在while循環的條件:while((line = br.readLine()) != null)

你讀每一個迭代線和LEVE的循環,如果返回的readLine null

如果讀取了'\ n',readLine只返回null,如果eof已達到(= socked關閉)並返回一個String。

,如果你想退出上的readLine循環,你可以省略整個while循環UND只是做:

line = br.readLine()

+0

謝謝,我可以試試這個。 – Majid 2013-03-20 10:58:10

0
如果你想獲得什麼樣的插座不

被迫關閉簡單地使用ObjectInputStream的和的ObjectOutputStream ..

實施例:

ObjectInputStream ois; 
ObjectOutputStream oos; 

ois = new ObjectInputStream(connection.getInputStream()); 

String dataIn = ois.readUTF(); //or dataIn = (String)ois.readObject(); 

oos = new ObjectOutputStream(connection.getOutputStream()); 
oos.writeUtf("some message"); //or use oos.writeObject("some message"); 
oos.flush(); 

..... 
0

發生這種情況是因爲InputStream沒有準備好變紅,所以它會阻塞in.readLine()。 請試試這個:

boolean exitCondition= false; 

while(!exitCondition){ 
    if(in.ready()){ 
     if((line=in.readLine())!=null){ 
      // do whatever you like with the line 
     } 
    } 
} 

當然,你必須控制exitCondition。

其他選項可以使用nio軟件包,它允許讀取異步(不阻塞),但它取決於您的需要。

0

我嘗試了很多的解決方案,但唯一一個我發現這是不堵的執行是:

BufferedReader inStream = new BufferedReader(new 
InputStreamReader(yourInputStream)); 
String line; 
while(inStream.ready() && (line = inStream.readLine()) != null) { 
    System.out.println(line); 
} 

inStream.ready()返回false如果未來readLine()調用將阻塞執行。

相關問題