你可以这样做:
InputStream in = someBluetoothSocket.getInputStream();
int timeout = 0;
int maxTimeout = 8; // leads to a timeout of 2 seconds
int available = 0;
while((available = in.available()) == 0 && timeout < maxTimeout) {
timeout++;
// throws interrupted exception
Thread.sleep(250);
}
byte[] read = new byte[available];
in.read(read);
这样,您最初可以从具有特定超时的流中读取.如果你想在任何阅读时间实现超时,你可以尝试这样的事情:
Thread readThread = new ReadThread(); // being a thread you use to read from an InputStream
try {
synchronized (readThread) {
// edit: start readThread here
readThread.start();
readThread.wait(timeOutInMilliSeconds);
}
catch (InterruptedException e) {}
使用此方法,您可能需要某种事件处理程序来通知您的应用程序,如果该线程实际读取了输入流中的内容.
我希望有所帮助!
– – 编辑:
我没有使用任何处理程序实现了一个示例.
Socket s = new Socket("localhost", 8080);
final InputStream in = s.getInputStream();
Thread readThread = new Thread(new Runnable() {
public void run() {
int read = 0;
try {
while((read = in.read()) >= 0) {
System.out.println(new String(new byte[]{ (byte) read }));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
synchronized (readThread) {
readThread.start();
try {
readThread.wait(2000);
if(readThread.isAlive()) {
// probably really not good practice!
in.close();
System.out.println("Timeout exceeded!");
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}