I have a function that reads a message from the client with a timeout of 100ms. In my code, I use this function in a loop until I get a string that is different than "" and that is how I know I got the message I needed and can continue my code. For some reason, it works for the first socket, but when I send what I received from socket to socket 2 and wait for socket2 to respond, I get bytesReceived = -1 even though socket2 is still connected and alive.
Code:
public String getMessage(int socketNumber) {
Socket socket = socket1;
if(socketNumber == 2){
socket = socket2;
}
byte[] message = new byte[4096];
int bytesReceived = 0;
try {
socket.setSoTimeout(100);
bytesReceived = socket.getInputStream().read(message);
} catch (SocketTimeoutException e) {
return "";
} catch (IOException e) {
throw new RuntimeException(e);
}
System.out.println("AMOUNT OF BYTES RECEIVED FROM" + socketNumber + " IS " + bytesReceived);
// Convert the message to a string.
return new String(message, 0, bytesReceived);
}
If a message is passed that is larger than your byte array, your code will not receive the whole message. Also, you might be better to wrap the
InputStreamin aReadersince some characters are two bytes and might be chopped in half between tworeadoperations.You could try something like: