我有一些奇怪的套接字行爲正在進行。我使用setSoTimeout設置了5秒的超時時間。在我的情況下,這應該是充足的時間。根據在線Java文檔,如果超時,應該拋出一個SocketTimeoutException
。它還表示套接字仍然有效。所以我想抓住它然後繼續。然而,而不是內部捕獲,外部捕獲IOException
捕捉的說法,當我輸出到日誌的細節,它說這是一個SocketTimeoutException
。另一個令人困惑的事情是,我將超時從5秒改爲15秒,並記錄每次讀取所花費的時間,時間總是在毫秒範圍內,甚至從未接近1秒。任何想法都非常感謝。Android - 套接字超時
ReadThread
代碼片段
@Override
public void run()
{
try
{
while (true)
{
byte[] sizeBuffer = new byte[BYTES_FOR_MESSAGE_SIZE];
int bytesRead = this.inputStream.read(sizeBuffer);
int length = 0;
for (int i = 0; i < BYTES_FOR_MESSAGE_SIZE; i++)
{
int bitsToShift = 8 * i;
int current = ((sizeBuffer[i] & 0xff) << bitsToShift);
length = length | current;
}
byte[] messageBuffer = new byte[length];
this.socket.setSoTimeout(5000); //5 second timeout
try
{
this.inputStream.read(messageBuffer);
}
catch(java.net.SocketTimeoutException ste)
{
Log.e(this.toString(), "---- SocketTimeoutException caught ----");
Log.e(this.toString(), ste.toString());
}
}
}
catch (IOException ioe)
{
Log.e(this.toString(), "IOException caught in ReadThread");
Log.e(this.toString(), ioe.toString());
ioe.printStackTrace();
}
catch (Exception e)
{
Log.e(this.toString(), "Exception caught in ReadThread");
Log.e(this.toString(), e.toString());
e.printStackTrace();
}
this.interfaceSocket.socketClosed();
}// end run