Here is the flow of my client/server.
Socket is created in main thread.
- Socket passes to Thread 1.
- Client sends data to server
- Server responds to client
- Server closes input stream, output stream, and socket by invoking
close()
- Socket returned to main thread, and then passed to Thread 2.
- Client writes data to server - no exception, no errors, server gets no data
- Client attempts to read data - no exceptions, no errors
How can I detect the problem that socket was closed?
try {
os = new DataOutputStream(this.socket.getOutputStream());
os.write(data);
os.flush();
System.out.println("Written " + data.length + " bytes");
} catch (IOException e) {
System.out.println("Client failed to write to stream");
System.out.println(e.getMessage());
e.printStackTrace();
}
The exception is never thrown. It says Written 60 bytes
. Any ideas?
UPDATE
Here is the way that I read the response. I wait for data, read first 4 bytes (which gives the the length of response), and keep reading until I read the specified length. This loop never ends because no data ever comes in.
is = new DataInputStream(this.socket.getInputStream());
while(true){
while(is.available() > 0){
bos.write(is.read());
}
if(contentLength == 0 && bos.size() > 3){
byte[] bytes = bos.toByteArray();
byte[] size = Arrays.copyOf(bytes, 4);
contentLength = ByteBuffer.wrap(size).getInt();
}
if(bos.size() - 4 < contentLength){
continue;
}
break;
}
available()
must return zero. – Umbilication