我遇到了一些奇怪的socket行为。我使用了setSoTimeout设置了5秒的超时时间,这在我的情况下应该足够了。根据在线Java文档,如果超时了应该抛出SocketTimeoutException,并且它说socket仍然有效。所以我想要捕获它,然后继续执行。然而,不是内部catch语句,而是外部的IOException catch语句捕获了异常,并且当我输出日志详细信息时,它说是一个SocketTimeoutException。另一个令人困惑的事情是,我将超时时间从5秒更改为15秒,并记录每次读取所需的时间,时间总是在毫秒范围内,甚至没有接近1秒。非常感谢您的任何想法。
ReadThread代码片段
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