[英]not able to catch -1 response from socket read
我有一個充當客戶端線程的類。 在該類中,我有一個run
方法,該方法處理套接字的讀寫操作。 我的運行方法如下所示:
public void run(){
System.out.println("New connection at " + new Date() + "\n");
try {
DataInputStream in = new DataInputStream (threadSocket.getInputStream());
out = new DataOutputStream (threadSocket.getOutputStream());
while (running){
// read input from client
byte[] input = new byte [200];
int count = in.read(input);
if (count == -1) {
running = false;
break;
}
String msg = new String(input, 0, count);
// parse in going message
messageParsing(msg);
// respond to client
response();
}
}
catch (IOException ex) {ex.printStackTrace();}
finally {
try {
threadSocket.close();
System.out.println("Connection closed.\n");
} catch (IOException ex) {ex.printStackTrace();}
}
}
我創建了一個固定大小的字節數組,並且正在從套接字讀取數據。 輸入的數據的可用長度為147和61,如果輸入數據的長度為0,則沒有任何意義。 我想在計數為-1時關閉套接字,但我不成功。 似乎當沒有數據時,count為0時,它只是一直試圖從套接字讀取數據而被卡住。
我該如何解決這個問題? 我究竟做錯了什么? 任何幫助,將不勝感激。
當另一通信側實際上已關閉其輸出時,流只能返回-1,即用信號通知結束,從而確保不再傳輸任何數據。
無法復制。 您的代碼永遠不會從讀取中獲得零。 如果您沒有得到-1,那是因為對等方永遠不會關閉連接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.