1

I am making an android app and sending an xml to an ip address. I should get back an xml as response but bytes in inputstream buffer is always empty. I am using following code:

 String sMessage = "<Server><CONNECT><IP>192.168.1.14</IP><Client_ID>123</CLIENT_GUID></CONNECT></Server>";

 Socket clientSocket = null;
 clientSocket = new Socket("192.168.252.148",34543);
 PrintWriter pw = new PrintWriter(clientSocket.getOutputStream(),true);

 pw.write(sMessage);
 InputStream in = clientSocket.getInputStream();
 byte[] buffer = new byte[in.available()];
 System.out.println("buffer size: "+buffer.length);

 pw.close();
 in.close();
 clientSocket.close();

Any idea why am i not getting bytes in my inputstream. Thanks in advance.

Piscean
  • 3,069
  • 12
  • 47
  • 96

3 Answers3

1

http://docs.oracle.com/javase/6/docs/api/java/io/InputStream.html#available()

The available method for class InputStream always returns 0.

This method should be overridden by subclasses.

Try wrapping using a BufferedInputStream.

BufferedInputStream in = new BufferedInputStream(clientSocket.getInputStream());
Community
  • 1
  • 1
Ken Wolf
  • 23,133
  • 6
  • 63
  • 84
0

I should get back an xml as response but bytes in input stream buffer

Maybe so, but not instantaneously, which is what your code assumes. There are few if any correct uses of available(), and this isn't one of them. Just block in the read.

user207421
  • 305,947
  • 44
  • 307
  • 483
-1

.available() can not be used in inter-process communication (serial included), since it only checks if there is data available (in input buffers) in current process.

In serial communication, when you send a massage and then immediately call available() you will mostly get 0 as serial port did not yet reply with any data.

The solution is to use blocking read() in a separate thread (with interrupt() to end it):

try this Thread interrupt not ending blocking call on input stream read

on some streams (such as BufferedInputStream, that have an internal buffer), some bytes are read and kept in memory, so you can read them without blocking the program flow. In this case, the available() method tells you how many bytes are kept in the buffer.

new BufferedOutputStream(clientSocket.getOutputStream()));
new BufferedInputStream (clientSocket.getInputStream())
Community
  • 1
  • 1
Sunil Kumar
  • 7,086
  • 4
  • 32
  • 50
  • 1
    Your first two paragraphs are completely incorrect. It is open to implementations to check the contents of kernel buffers, and the Socket input stream's available method does just that, via FIONREAD. I would expect serial or parallel port streams to do the same. – user207421 Jun 29 '13 at 03:40