Weird TCP Sockets on WearOS

April 30th, 2020

Usually, the following code just works:

Socket socket = ...
OutputStream os = socket.getOutputStream();

while (... data available ...) {
    os.write(buffer, 0, read);
}

socket.close();

But the last few (hundred?) bytes don’t get to the receiver. You are right, I’m closing the socket too early, having no guarantee whether the buffer has been sent. Just to prove, this is the real reason:

while (... data available ...) {
    os.write(buffer, 0, read);
}

Thread.sleep(5000);

socket.close();

The above code makes the job. Of course, in an unacceptable way. We need a correct solution. Okay, look here:

while (... data available ...) {
    os.write(buffer, 0, read);
}

socket.shutdownOutput();
socket.getInputStream().read(buffer);
socket.close();

In the example above, the receiver should detect the end of the incoming data (and it does). The sender should block on the read() until data is available or the stream/socket gets closed on the other side. But it does not. It returns almost immediately and closes the socket. Same result: a few last bytes are truncated.

Removing the “shutdownOutput()” call makes the sender wait. Unfortunately, it makes the received wait as well (as expected).

Are the sockets broken on WearOS?

The above situation does happen in the proxy mode. To be continued: test it with a direct network connection.


Next: Tracker on GitHub

Previous: Debugging on WearOS

Main Menu