Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't read socket InputStream on Jelly Bean

I have a TCP socket connection which works well on Android 2.3 but now facing some problems on Android 4.1. The problem is that InputStream.read() method always returns -1 (without blocking), like the connection is closed.

Creating socket:

SocketFactory socketFactory = SocketFactory.getDefault();
Socket socket = socketFactory.createSocket("c.whatsapp.net", 5222);
socket.setSoTimeout(3*60*1000);
socket.setTcpNoDelay(true);

Retrieving input and output streams and writing some initial data:

InputStream inputStream = new BufferedInputStream(socket.getInputStream());
OutputStream outputStream = new BufferedOutputStream(socket.getOutputStream());

outputStream.write(87);
outputStream.write(65);
outputStream.write(1);
outputStream.write(2);
outputStream.flush();

Then, this condition always passes without blocking:

int c = inputStream.read();
if (c < 0) {
    Log.d(TAG, "End of stream");
}

This code is running in a background thread. And it was working on Gingerbread.

Tried to use InputStreamReader and OutputStreamWriter instead of direct streams - no effect.

like image 622
Alexander Sukharev Avatar asked Mar 01 '13 09:03

Alexander Sukharev


1 Answers

I have seen that very same error before, although this answer might look offtopic give it a chance and let me know if it worked, for some reason sockets are having strange behavior on jellybean even when they were working completely fine in lower android versions, the way I fixed this issue was to move the targetSdkVersion to jelly bean as well as the Project Build Target under Android properties of the project, didn't modify one single line of code, just that, and for some reason it does the trick...

Hope this helps.

Regards!

like image 114
Martin Cazares Avatar answered Oct 13 '22 21:10

Martin Cazares