简体   繁体   中英

Android sockets: receiving data in real-time

I have another device & application transmitting data in real-time (every few ms) and on my receiving device, I want to:

1) read/receive this data, and 2) use it to update a UI element (a dynamic graph in this case)

The data sender uses a socket in a background service, using AsyncTasks every few ms to send data. To initialize, it does the following:

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

And to periodically send data it does:

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

    }

How should I go about receiving this data in my application? Should I also use a background service with AsyncTasks that try to read from the socket every few ms? How about communicating with the UI thread?

There are many ways to do this. The simplest would be to use blocking reads in the doInBackground method of an AsyncTask and call publishProgress() to forward the new data to the UI thread.

Then implement onProgressUpdate with code (running in the UI thread) that updates the screen.

You should be aware that your read may not receive the entire message that you sent -- you may need to read more data and append it to the input received so far until you have an entire JSON message.

By blocking reads, I mean something like this (in pseudo code):

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

The copy-out-of-the-buffer is necessary because the onProgressUpdate does not happen immediately so you need to be sure the next message does not overwrite the current one before it gets handled.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM