簡體   English   中英

在 Android 中的 BluetoothSocket inputstream.read() 中實現超時

[英]Implement a timeout in BluetoothSocket inputstream.read() in Android

是否可以在 Android 中的 BluetoothSocket 的 inputstream.read() 函數中實現超時?

我試過使用 Thread.sleep() 但這只會暫停我的活動。

- -更新 - -

我有一個想法,在此處創建 2 個線程代碼(t1 和 t2),其中每個線程中斷另一個線程,其中一個(t1)執行 sleep(5000)然后中斷另一個線程(t2),從另一側另一個線程( t2)如果在讀取輸入流檢測到一些字符為 0x0D 中斷另一個線程(t1),但這是我的問題,有人可以幫助我嗎? 因為我沒有使用線程的interrupt()方法,希望有人能幫幫我,謝謝...

- -更新 - -



        public void run(){
        while(true){
            try {
            char r;
            String respuesta = "";
            while (true) {
                    r = (char) mmInStream.read();
                respuesta += r;
                if (r == 0x3e) {
                break;
                    }
                }
            respuesta = respuesta.replaceAll(" ", "");
            Log.d("respuesta", respuesta);
            rHandler.obtainMessage(MESSAGE_READ, -1, -1, respuesta).sendToTarget();
            } catch (IOException readException) {
            Log.e("ServicioGeneral", "Error de lectura", readException);
            this.interrupt();
            connectionLost();
            // posibly break();
            }
        }
    }

這是我在不同線程中出現某些內容時的實現,問題是如果我沒有從 de mmInStream 中獲取 0x3e 字符,則會達到超時。

我想在第二個例子中我必須使用notifyAll(),但是,我什么時候必須啟動readThread()?

謝謝你,@weeman

你可以這樣做:

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

    }

用於超時讀取套接字的 Kotlin 擴展函數:

fun InputStream.read(
  buffer: ByteArray,
  offset: Int,
  length: Int,
  timeout: Long
): Int = runBlocking {
    val readAsync = async {
        if (available() > 0) read(buffer, offset, length) else 0
    }
    var byteCount = 0
    var retries = 3
    while (byteCount == 0 && retries > 0) {
        withTimeout(timeout) {
            byteCount = readAsync.await()
        }
        delay(timeout)
        retries--
    }
    byteCount
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM