I'm creating a java Client program that sends a command to server and server sends back an acknowledgement and a response string.
The response is sent back in this manner
client -> server : cmd_string
server -> client : ack_msg(06)
server -> client : response_msg
When I try to read the input either I'm only able to read to read just the acknowledgement message with one inputstream
My client program is able to read the message somehow(hacky method). To read the input I have to read the ack msg using Bufferedreader.
Client.java
try {
Socket clientSocket = new Socket(SERVER_ADDRESS, TCP_SERVER_PORT);// ip,port
System.out.println(" client Socket created .. ");
PrintWriter outToServer = new PrintWriter(clientSocket.getOutputStream(), true);
String ToServer = command;
outToServer.println(ToServer);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
//
// while (!in.ready()) {
// }
System.out.println(in.read()); // Read one line and output it
// ===
byte[] messageByte = new byte[1000];//assuming msg size -need to know eact msg size ?
boolean end = false;
String dataString = "";
int bytesRead = 0;
try {
DataInputStream in1 = new DataInputStream(clientSocket.getInputStream());
//
while (!end) {
bytesRead = in1.read(messageByte);
dataString += new String(messageByte, 0, bytesRead);
if (dataString.length() > 0) {
end = true;
}
}
System.out.println("MESSAGE: " + dataString);
} catch (Exception e) {
e.printStackTrace();
}
// ===
in.close();
clientSocket.close();
System.out.print("connection closed");
} catch (Exception e) {
System.out.print("Whoops! It didn't work!\n");
e.printStackTrace();
}
Output
client Socket created ..
response:6
MESSAGE: ³CO³0³Œ
connection closed
When I skip step 1
client Socket created ..
MESSAGE: -
connection closed
How can I write code that reads all the input from server(acknowledgement msg & response message & it should also check the size of data and read accordingly)?
Referred to How to read all of Inputstream in Server Socket JAVA
Thanks
These statements force the stream to be closed as soon as at least 1 byte is sent.
dataString += new String(messageByte, 0, bytesRead);
if (dataString.length() > 0) {
end = true;
}
As soon as the ack of 6 is received the connection is closed. If the ack is ignored, the response may be sent in multiple packets, the connection would close after the first packet is received.
You must be able to determine when the ack and the response have ended.