[英]InputStream receive method blocking
我陷入以下問題。 我已經創建了到遠程回顯服務器的連接。 以下方法用於接收從服務器接收的字節:
public byte[] receive() {
byte[] resultBuff = new byte[0];
byte[] buff = new byte[4096];
try {
InputStream in = socket.getInputStream();
int k = -1;
while((k = in.read(buff, 0, buff.length)) != -1) {
System.out.println(k);
byte[] tbuff = new byte[resultBuff.length + k]; // temp buffer size = bytes already read + bytes last read
System.arraycopy(resultBuff, 0, tbuff, 0, resultBuff.length); // copy previous bytes
System.arraycopy(buff, 0, tbuff, resultBuff.length, k); // copy current lot
resultBuff = tbuff; // call the temp buffer as your result buff
String test = new String(resultBuff);
System.out.println(test);
}
System.out.println(resultBuff.length + " bytes read.");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return resultBuff;
}
我能夠從服務器獲得以下響應:
Connection to MSRG Echo server established
問題在於循環陷入了in.read()的第二次執行。 我了解這是由於服務器未發送任何EOF信息等。
我不確定以下兩種解決方案中的哪一種是正確的,以及哪種實現方式是正確的:
來自服務器的每個消息都將由新執行的receive()方法讀取。 如何防止in.read()方法阻塞?
在應用程序退出之前,receive()方法內部的循環應保持活動狀態。 這意味着我的實現當前使用in.read()錯誤。 應該以哪種方式實施。
這個問題的關鍵是您使用“消息”一詞。 TCP中沒有消息,只有字節流。 如果需要消息,則必須自己實現:一次讀取一個字節,直到獲得完整的消息,進行處理,沖洗並重復。 您可以使用BufferedInputStream攤銷單字節讀取的成本。
但是回顯服務器中沒有消息。 因此,您的讀取和累積策略不適當。 隨便回聲,無論收到什么。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.