Hi,
I think my question is similar to EzzatScreen's below. I have a threaded client/server application using sockets to communicate back-and-forth. I was under the impression the socket.getInputStream.read() blocked until there was data available; however, this doesn't appear to be happening in my code.
This is the run() method from my Connection class:
public void run() {
try {
byte[] buffer;
socket.getInputStream().read(buffer = new byte[socket.getInputStream().available()]);
socket.getOutputStream().write(MessageController.processMessage(new Message(buffer)).getXML());
socket.getOutputStream().flush();
socket.close();
} catch (UnknownHostException uhe) {
uhe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
} // run
Basically, the other end will dump all the data into the stream at once. I simply want to have read() block until the available() data length from the input stream isn't 0. At that time, I want to create a byte[] array buffer of the exact length of available bytes, read() the input stream bytes into the buffer, and then do something with the buffer (in the latter case, I'm writing a reply back after some processing).
The problem is that read() is getting called [seemingly] right away, and my byte[] array buffer ends up being zero-length, so when I try to process the data in subsequent methods, the program crashes. socket.getInputStream.available() is returning 0 and thus buffer.length ends up equaling 0.
How can I get read() to block until data is available, and then create a byte array that is exactly the size of the available data in the input stream? I thought the code above was doing that. =/
TIA
Oh, here is the code on the other end, if that helps:
public static Message sendMessage(Message message) {
Message replyMessage = null;
try {
Socket socket = new Socket(GlobalDataStore.getServerAddress(), GlobalDataStore.getServerPort());
socket.getOutputStream().write(message.getXML());
socket.getOutputStream().flush();
byte[] buffer;
socket.getInputStream().read(buffer = new byte[socket.getInputStream().available()]);
replyMessage = new Message(buffer);
socket.close();
} catch (UnknownHostException uhe) {
uhe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return replyMessage;
} // sendMessage
Essentially, it's doing pretty much the same thing with read() and write() reversed in sequence. It's also having the same problem, I believe.