簡體   English   中英

Android套接字:實時接收數據

[英]Android sockets: receiving data in real-time

我有另一台設備和應用程序實時傳輸數據(每隔幾毫秒),在我的接收設備上,我想:

1)讀取/接收此數據,以及2)使用它來更新UI元素(在這種情況下為動態圖)

數據發送方在后台服務中使用套接字,每隔幾毫秒使用AsyncTasks發送數據。 要初始化,它會執行以下操作:

echoSocket = new Socket(HOST, PORT);
out = new PrintWriter(echoSocket.getOutputStream(), true);

並定期發送數據:

static class sendDataTask extends AsyncTask<Float, Void, Void> {

        @Override
        protected Void doInBackground(Float... params) {
            try { 
                JSONObject j = new JSONObject();
                j.put("x", params[0]);
                j.put("y", params[1]);
                j.put("z", params[2]);
                String jString = j.toString();
                out.println(jString);
            } catch (Exception e) {
                Log.e("sendDataTask", e.toString());
            }
            return null;
        }

    }

我應該如何在我的應用程序中接收這些數據? 我是否還應該使用AsyncTasks的后台服務,每隔幾毫秒嘗試從套接字讀取一次? 如何與UI線程通信?

有很多方法可以做到這一點。 最簡單的方法是在AsyncTask的doInBackground方法中使用阻塞讀取,並調用publishProgress()將新數據轉發到UI線程。

然后使用更新屏幕的代碼(在UI線程中運行)實現onProgressUpdate。

您應該知道您的讀取可能不會收到您發送的整個消息 - 您可能需要讀取更多數據並將其附加到目前為止收到的輸入,直到您有完整的JSON消息。

通過阻止讀取,我的意思是這樣的(在偽代碼中):

open a socket connected to the sender
is = socket.getInputStream()
initialize buffer, offset, and length
while the socket is good
    bytesRead = is.read(buffer, offset, length)
    if(bytesRead <= 0)
        bail out you have an error
    offset += bytesRead;
    length -= bytesRead 
    if(you have a complete message)
        copy the message out of the buffer (or parse the message here into
          some other data structure)
        publishProgress(the message)
        reset buffer offset and length for the next message.
         (remember you may have received part of the following message)
    end-if
end-while

復制輸出緩沖區是必要的,因為onProgressUpdate不會立即發生,因此您需要確保下一條消息在處理之前不會覆蓋當前消息。

暫無
暫無

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

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