android read设置超时时间,在Android中的BluetoothSocket inputstream.read()中实现超时

这篇博客介绍了如何在Java中处理输入流的超时读取,通过示例展示了如何创建一个读取线程,并在指定时间内等待数据,如果超时则关闭输入流。同时,它还提及了线程同步的概念,确保线程安全地读取和处理数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

你可以这样做:

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();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值