0
我遇到以下問題。我創建了一個到遠程回顯服務器的連接。下面的方法用於接收從服務器接收的字節數:InputStream接收方法阻塞
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信息等。
我不知道它下面的兩個解決方案是正確的,以何種方式實現它:
來自該服務器的每一個信息都將被接受()方法的一個新的執行讀取。如何防止in.read()方法被阻塞?
receive()方法中的循環應保持活動狀態,直到應用程序退出。這意味着我的實現目前正在使用in.read()錯誤。這應該以何種方式實施。
非常感謝!我需要在你的回覆中問清楚你的意思是「沖洗」。在我的例子中,ASCII 13是消息的分隔符。 – mgerstner
沖洗並重復。這是一個玩笑多麗絲。 – EJP